What is Cherry-Pick?
Cherry-picking creates a new commit on your current branch with the same changes as an existing commit from another branch. The new commit has a different hash but the same diff.Basic Cherry-Pick
Applying a Single Commit
To apply a specific commit to your current branch:a1b2c3d and creates a new commit on main.
Applying Multiple Commits
To cherry-pick a range of commits:Cherry-Pick Options
Edit the Commit Message
Modify the commit message before applying:Record the Origin
Add a “cherry picked from” line to the commit message:Use
-x when cherry-picking between public branches (like backporting a fix). Don’t use it for private branches as the information is not useful to others.Apply Without Committing
Apply the changes but don’t create a commit:Sign Off the Commit
Add a Signed-off-by trailer:Handling Conflicts
When cherry-picking causes conflicts, Git pauses and marks the conflicts:Aborting a Cherry-Pick
To cancel the cherry-pick and return to the pre-cherry-pick state:Skipping a Commit
When cherry-picking multiple commits, skip the current one:Cherry-Picking Merge Commits
Merge commits have multiple parents, so you must specify which parent to use:-m 1uses the first parent (usually the branch you merged into)-m 2uses the second parent (usually the branch being merged)
Common Use Cases
Backporting a Bug Fix
Apply a fix frommain to a release branch:
Moving a Commit to the Wrong Branch
If you committed to the wrong branch:- Note the commit hash:
git log - Switch to the correct branch:
git checkout correct-branch - Cherry-pick the commit:
git cherry-pick abc123 - Switch back:
git checkout wrong-branch - Remove the commit:
git reset --hard HEAD^
Applying Specific Features
Cherry-pick feature commits from a development branch:Testing a Fix Before Merging
Advanced Examples
Cherry-Pick with Strategy Options
Use merge strategies when cherry-picking:Cherry-Pick Multiple Non-Consecutive Commits
Cherry-Pick and Combine Commits
Programmatic Cherry-Picking
Cherry-pick commits matching a pattern:Cherry-Pick vs. Rebase vs. Merge
| Operation | Use Case | History Impact |
|---|---|---|
| Cherry-pick | Apply specific commits | Duplicates commits |
| Rebase | Update feature branch | Rewrites history |
| Merge | Integrate branches | Preserves history |
Best Practices
-
Use
-xfor public branches - Always record the source when backporting fixes to release branches - Prefer merging over cherry-picking - Cherry-picking duplicates commits. When possible, merge branches instead
- Test after cherry-picking - The same changes may behave differently in different contexts
- Document why you cherry-picked - Use clear commit messages explaining why this specific commit was cherry-picked
- Avoid cherry-picking many commits - If you need many commits from a branch, consider merging instead
- Be careful with dependencies - Ensure all dependencies are present when cherry-picking individual commits
