On This Page
How to Cherry-Pick a Commit in Git (Step-by-Step)
Quick Answer: git cherry-pick <commit-hash> applies the changes from a specific existing commit onto your current checked-out branch. It is ideal when you need a single bug fix or feature from another branch without merging all of that branch’s changes.
When Should You Cherry-Pick?
- Hotfixes: A bug fix was committed on a
featurebranch, but needs to be applied immediately tomainor production. - Selective Merging: You want 1 or 2 commits out of a 20-commit feature branch.
- Recovering Lost Commits: Copying a commit from an abandoned branch.
Step-by-Step Guide
Step 1: Find the Commit Hash
Locate the SHA-1 hash of the commit you want to copy using git log:
$ git log --oneline feature-branch
# Output:
# a1b2c3d Add critical security fix
# e4f5g6h Experimental UI work
Step 2: Switch to Target Branch
Check out the destination branch where you want to apply the commit:
$ git checkout main
Step 3: Run git cherry-pick
Execute git cherry-pick with the commit hash:
$ git cherry-pick a1b2c3d
Git applies the changes and creates a new commit on main with a unique commit hash containing the same diff and commit message.
Useful Cherry-Pick Options
Cherry-Pick Multiple Commits
# Cherry-pick multiple individual commits
$ git cherry-pick a1b2c3d e4f5g6h
# Cherry-pick a range of commits (from A to B)
$ git cherry-pick a1b2c3d..e4f5g6h
Cherry-Pick Without Committing (-n / --no-commit)
If you want to apply the changes to your workspace and index without automatically creating a commit:
$ git cherry-pick -n a1b2c3d
Handling Conflicts During Cherry-Pick
If the cherry-picked changes conflict with your current branch code:
# 1. Edit conflicting files and remove markers
# 2. Stage resolved files
$ git add resolved-file.js
# 3. Continue cherry-pick
$ git cherry-pick --continue
# Or abort the operation cleanly
$ git cherry-pick --abort
For more on commit objects and branch pointers, read /git-commit and /git-branch.