Git高级操作

交互式Rebase

# Rebase last 5 commits interactively
git rebase -i HEAD~5

# In editor, use commands:
# pick   = keep commit as-is
# reword = keep but edit message
# edit   = keep but pause to amend
# squash = merge into previous commit
# fixup  = squash, discard message
# drop   = remove commit

# Squash feature commits before merging
git rebase -i main

Cherry-pick

# Apply specific commit to current branch
git cherry-pick abc1234

# Cherry-pick range of commits
git cherry-pick abc1234^..def5678

# Cherry-pick without committing (to edit)
git cherry-pick --no-commit abc1234

# Abort on conflict
git cherry-pick --abort

Stash

# Save work in progress
git stash push -m "WIP: feature X"

# Include untracked files
git stash push --include-untracked

# List all stashes
git stash list

# Apply and remove stash
git stash pop stash@{0}

# Apply without removing
git stash apply stash@{0}

# Create branch from stash
git stash branch new-feature stash@{0}

Reflog — 找回丢失的提交

# Show all HEAD movements
git reflog

# Recover after accidental reset
git reset --hard HEAD~3     # oops!
git reflog                  # find lost commit hash
git reset --hard abc1234    # restore it

# Recover deleted branch
git checkout -b recovered abc1234

Bisect — 找出引入bug的提交

# Binary search for bug introduction
git bisect start
git bisect bad              # current = broken
git bisect good v1.0.0      # last known good tag
# Git checks out middle commit
# Test it, then:
git bisect good             # or: git bisect bad
# Repeat until Git identifies the offending commit
git bisect reset            # return to original HEAD

实用配置

git config --global alias.lg "log --oneline --graph --all"
git config --global alias.undo "reset HEAD~1 --mixed"
git config --global pull.rebase true
git config --global fetch.prune true
git config --global rebase.autoStash true