git cherry-pick — Picking Specific Commits
The git cherry-pick command applies a specific commit from one branch to another. Instead of merging or rebasing an entire branch, you pick just the commits you need.
When to Use Cherry-Pick
- You need a single bug fix from another branch, but not everything else
- A commit was made on the wrong branch and needs to be applied to the right one
- You want to backport a fix from a development branch to a release branch
How It Works
Before cherry-pick:
A — B — C (main)
\
D — E — F (feature)
After git cherry-pick E (from main):
A — B — C — E' (main)
\
D — E — F (feature)
Commit E' has the same changes as E, but it's a new commit with a new SHA. The original commit E remains on the feature branch.
Basic Usage
git cherry-pick abc1234 # Apply a specific commit by SHA
git cherry-pick feature~1 # Apply the second-to-last commit from feature
Cherry-Pick vs Merge vs Rebase
| Cherry-Pick | Merge | Rebase | |
|---|---|---|---|
| Scope | One (or few) commits | Entire branch | Entire branch |
| History | Duplicates the commit | Adds merge commit | Replays commits |
| Use case | Selective changes | Integrate branches | Clean up history |
Try it!
Practice cherry-picking a commit from one branch to another:
- Create an initial commit:
echo "base" > file.txt && git add file.txt && git commit -m "Initial commit"
- Create a feature branch with two commits:
git checkout -b featureecho "feature A" > a.txt && git add a.txt && git commit -m "Add feature A"echo "feature B" > b.txt && git add b.txt && git commit -m "Add feature B"
- Note the SHA of "Add feature A":
git log --oneline - Switch back to main:
git checkout main - Cherry-pick only "Add feature A":
git cherry-pick <SHA>(use the SHA from step 3) - Verify:
git log --oneline— main now has the cherry-picked commit - Check:
ls— you should seea.txtbut notb.txt
Cherry-Picking Multiple Commits
You can pick several commits at once:
git cherry-pick abc1234 def5678 # Pick specific commits
git cherry-pick abc1234..def5678 # Pick a range (exclusive of first)
git cherry-pick abc1234^..def5678 # Pick a range (inclusive of first)
Handling Conflicts
If the cherry-picked commit conflicts with your current branch:
- Resolve the conflicts in the affected files
- Stage the resolved files:
git add <file> - Continue:
git cherry-pick --continue
To abort: git cherry-pick --abort
Key Points
- Cherry-pick copies a specific commit to your current branch as a new commit
- The original commit stays on its source branch — nothing is moved or deleted
- Use it for selective changes when merge or rebase would bring too much
- Like rebase, it creates new commits with new SHAs — the changes are duplicated, not moved