Advanced Git Techniques
Move beyond basic Git commands and master these advanced techniques.
Interactive Rebase
Clean up your commit history:
# Rebase last 5 commits
git rebase -i HEAD~5
Options in interactive mode:
pick- Keep commit as isreword- Change commit messagesquash- Combine with previous commitfixup- Like squash, but discard messagedrop- Remove commit
Cherry-Picking
Apply specific commits to another branch:
# Apply a single commit
git cherry-pick <commit-hash>
# Apply multiple commits
git cherry-pick <hash1> <hash2>
# Cherry-pick without committing
git cherry-pick -n <commit-hash>
Stashing Like a Pro
Save work without committing:
# Stash with message
git stash push -m "WIP: feature X"
# List all stashes
git stash list
# Apply specific stash
git stash apply stash@{2}
# Create branch from stash
git stash branch new-branch stash@{0}
Git Bisect
Find the commit that introduced a bug:
git bisect start
git bisect bad # Current commit is bad
git bisect good v1.0.0 # v1.0.0 was good
# Git will checkout commits for you to test
# Mark each as good or bad
git bisect good
git bisect bad
# When done
git bisect reset
Reflog - Your Safety Net
Recover "lost" commits:
# View all actions
git reflog
# Recover a deleted branch
git checkout -b recovered-branch HEAD@{5}
# Undo a hard reset
git reset --hard HEAD@{2}
Worktrees
Work on multiple branches simultaneously:
# Create a worktree for a branch
git worktree add ../feature-branch feature-branch
# List worktrees
git worktree list
# Remove worktree
git worktree remove ../feature-branch
Useful Aliases
Add to your .gitconfig:
[alias]
co = checkout
br = branch
st = status
lg = log --oneline --graph --all
undo = reset HEAD~1 --soft
amend = commit --amend --no-edit
Conclusion
These advanced Git techniques will make you more productive. Practice them until they become second nature.