Git Cherry-Pick a Specific Commit
Use git cherry-pick to apply a specific commit from one branch to another. Copy individual changes without merging entire branches.
git cherry-pick <commit-hash>Detailed Explanation
What Does git cherry-pick Do?
git cherry-pick takes a single commit (identified by its hash) and applies it to your current branch as a new commit. The original commit remains untouched on its source branch. This is useful when you need one specific change without bringing over an entire branch.
How It Works
- Git reads the diff introduced by the target commit.
- Git applies that diff to your current working tree.
- If the patch applies cleanly, Git creates a new commit with the same message but a different hash.
Step-by-Step Example
# Find the commit hash you want
git log --oneline feature/payments
# Example output: a1b2c3d Fix currency rounding bug
# Switch to the branch that needs the fix
git checkout main
# Cherry-pick the commit
git cherry-pick a1b2c3d
Cherry-Picking Multiple Commits
You can cherry-pick a range of commits:
git cherry-pick a1b2c3d..f4e5d6a
Or pick several individual commits:
git cherry-pick a1b2c3d f4e5d6a 7g8h9i0
Handling Conflicts
If the cherry-picked commit conflicts with your current branch, Git will pause and ask you to resolve the conflicts manually. After resolving:
git add .
git cherry-pick --continue
To abort the operation entirely, run git cherry-pick --abort.
When to Avoid Cherry-Pick
Cherry-picking duplicates commits, which can cause confusion if the source branch is later merged. Use it sparingly — prefer merging or rebasing when you need all changes from a branch. Cherry-pick is best reserved for hotfixes and targeted backports.
Use Case
A critical bug fix was committed on a development branch, and the team needs to apply only that fix to the production release branch without merging unfinished features.