Git Cherry-pick: Apply Specific Commits to Another Branch
Learn how to use git cherry-pick to apply specific commits from one branch to another. Handle conflicts, cherry-pick ranges, and understand when cherry-pick is the right tool.
Detailed Explanation
Git Cherry-pick Guide
git cherry-pick applies the changes from one or more specific commits onto the current branch. Unlike merge or rebase, it targets individual commits rather than entire branches.
Basic Cherry-pick
# Apply a single commit to the current branch
git cherry-pick abc1234
# Apply multiple commits
git cherry-pick abc1234 def5678 ghi9012
# Apply a range of commits (exclusive start, inclusive end)
git cherry-pick abc1234..ghi9012
Cherry-pick Without Committing
# Apply changes but do not commit
git cherry-pick --no-commit abc1234
# This lets you modify the changes before committing
git add .
git commit -m "adapted: original feature for release branch"
Track the Source
# Add "(cherry picked from commit ...)" to the message
git cherry-pick -x abc1234
Handling Conflicts
# When cherry-pick conflicts:
# 1. Resolve conflicts in your editor
# 2. Stage the resolved files
git add <resolved-files>
# 3. Continue the cherry-pick
git cherry-pick --continue
# Or abort entirely
git cherry-pick --abort
Common Patterns
Hotfix from main to release branch:
git checkout release/v2.1
git cherry-pick <hotfix-commit-hash>
Backport a feature to an older version:
git checkout release/v1.x
git cherry-pick abc1234..def5678
When NOT to Cherry-pick
- If you need the entire branch, use
mergeorrebase - Cherry-picking creates duplicate commits with different hashes
- Excessive cherry-picking makes history hard to follow
- Consider if a proper merge workflow would be better
Use Case
Cherry-pick is essential for hotfix workflows. When a critical bug fix lands on main, it often needs to be applied to release branches without merging the entire main branch. It is also used for backporting features to LTS branches, selectively applying commits when branches have diverged significantly, and recovering specific changes from abandoned branches.