Tour of Git
History & Undoing Changes / Lesson 3.8

git cherry-pick — Picking Specific Commits

The git cherry-pick command applies a specific commit from one branch to another. Instead of merging or rebasing an entire branch, you pick just the commits you need.

When to Use Cherry-Pick

  • You need a single bug fix from another branch, but not everything else
  • A commit was made on the wrong branch and needs to be applied to the right one
  • You want to backport a fix from a development branch to a release branch

How It Works

Before cherry-pick:
A — B — C        (main)
     \
      D — E — F  (feature)

After git cherry-pick E (from main):
A — B — C — E'   (main)
     \
      D — E — F  (feature)

Commit E' has the same changes as E, but it's a new commit with a new SHA. The original commit E remains on the feature branch.

Basic Usage

git cherry-pick abc1234       # Apply a specific commit by SHA
git cherry-pick feature~1     # Apply the second-to-last commit from feature

Cherry-Pick vs Merge vs Rebase

Cherry-PickMergeRebase
ScopeOne (or few) commitsEntire branchEntire branch
HistoryDuplicates the commitAdds merge commitReplays commits
Use caseSelective changesIntegrate branchesClean up history

Try it!

Practice cherry-picking a commit from one branch to another:

  1. Create an initial commit:
    • echo "base" > file.txt && git add file.txt && git commit -m "Initial commit"
  2. Create a feature branch with two commits:
    • git checkout -b feature
    • echo "feature A" > a.txt && git add a.txt && git commit -m "Add feature A"
    • echo "feature B" > b.txt && git add b.txt && git commit -m "Add feature B"
  3. Note the SHA of "Add feature A": git log --oneline
  4. Switch back to main: git checkout main
  5. Cherry-pick only "Add feature A": git cherry-pick <SHA> (use the SHA from step 3)
  6. Verify: git log --oneline — main now has the cherry-picked commit
  7. Check: ls — you should see a.txt but not b.txt

Cherry-Picking Multiple Commits

You can pick several commits at once:

git cherry-pick abc1234 def5678     # Pick specific commits
git cherry-pick abc1234..def5678    # Pick a range (exclusive of first)
git cherry-pick abc1234^..def5678   # Pick a range (inclusive of first)

Handling Conflicts

If the cherry-picked commit conflicts with your current branch:

  1. Resolve the conflicts in the affected files
  2. Stage the resolved files: git add <file>
  3. Continue: git cherry-pick --continue

To abort: git cherry-pick --abort

Key Points

  • Cherry-pick copies a specific commit to your current branch as a new commit
  • The original commit stays on its source branch — nothing is moved or deleted
  • Use it for selective changes when merge or rebase would bring too much
  • Like rebase, it creates new commits with new SHAs — the changes are duplicated, not moved
🎯

Goal

Cherry-pick a specific commit from the feature branch onto main

Terminal
$

No commits yet. Run `git init` and create your first commit.