git cherry-pick <sha> takes the changes from a specific commit and
applies them to your branch. No full history, no merge, no rebase.
Just that one commit.
Basic form
git switch main
git cherry-pick a1b2c3d
# creates a new commit on main with the same content
# as a1b2c3d, but with a new SHA
The commit message is copied as-is. You can append a
cherry-picked from annotation:
git cherry-pick -x a1b2c3d
# Appends to the message:
# (cherry picked from commit a1b2c3d...)
This is useful for audits: you can see that the commit is a copy of another.
Typical scenarios
Hotfix across multiple release branches.
# Fixed a bug on main
git switch main
git commit -m "fix: handle null in user.profile"
# SHA = a1b2c3d
# Ported to release/v1.4
git switch release/v1.4
git cherry-pick a1b2c3d
# And to release/v1.5
git switch release/v1.5
git cherry-pick a1b2c3d
Rescue a useful commit from an abandoned branch.
Someone started a branch, left it, moved on. A few of those commits would be handy. cherry-pick the ones you need.
A commit landed on the wrong branch.
You committed to main instead of feature.
# Save the SHA
LAST=$(git rev-parse HEAD)
# Roll main back one commit
git reset --hard HEAD~1
# Apply it to feature
git switch feature
git cherry-pick $LAST
Range of commits
git cherry-pick A..B # commits after A up to B inclusive
# (A itself is excluded)
git cherry-pick A^..B # including A
They are applied one at a time in the original order. If any commit causes a conflict, Git stops.
--no-commit
git cherry-pick -n a1b2c3d
# Applies the changes but does not commit; leaves them in the index
Useful when you want to combine several cherry-picks into one commit:
git cherry-pick -n sha1 sha2 sha3
git commit -m "backport: nullability fixes from main"
Conflict
Resolved the same way as in merge or rebase:
# Conflict after cherry-pick: edit the files,
# remove the markers
git add <files>
git cherry-pick --continue
# or abort:
git cherry-pick --abort
Pitfalls
- Duplicate commits. After cherry-pick, the same set of changes exists in two commits with different SHAs. A subsequent merge between the branches can produce a spurious conflict.
- Dependencies. cherry-pick moves one commit without its predecessors. If that commit depended on something introduced in an earlier commit on the source branch, that earlier code may not exist on the target branch, and the build will break.
- Merge commits. cherry-pick on a merge commit requires the
-m Nflag to specify which parent is the "main" one. This is usually more complicated than it looks. In most cases it is easier to cherry-pick each individual commit from the merged branch separately.