Q19 of 40 · Git

When would you use `git cherry-pick`, and how do you cherry-pick a range of commits?

GitMidgitcherry-pickbackportreleaseworkflow

Short answer

Short answer: `git cherry-pick <sha>` applies a single commit's diff onto HEAD without merging the whole branch. Use it to backport a hotfix to a release branch or pull one commit from a colleague's branch. Range: `git cherry-pick A..B` (A exclusive).

Detail

git cherry-pick re-applies the diff introduced by one or more commits onto the current branch. The result is a new commit with a different SHA but the same changes. Unlike merging, you're not bringing in the commit's ancestry — just its delta.

Typical QA scenario: a critical fix was committed on main (e.g., a retry header in the API client) and a release/v2.4 branch needs the same fix without picking up unreleased features. Cherry-pick lets you transplant exactly that commit.

Range cherry-pick: git cherry-pick A..B picks commits from just after A up to and including B (A is exclusive). To include A itself, write git cherry-pick A^..B. You can also pass multiple individual SHAs: git cherry-pick sha1 sha2 sha3.

Conflict resolution: if a cherry-pick conflicts, Git pauses and lets you resolve files, then git cherry-pick --continue. Use --abort to abandon. The -x flag appends "(cherry picked from commit …)" to the message, which is helpful for traceability.

Overuse warning: cherry-pick is best for isolated commits. Applying many cherry-picks creates diverging histories that are hard to reconcile later — use feature branches and proper merges for large changes.

// EXAMPLE

# Switch to the release branch
git switch release/v2.4

# Cherry-pick a single hotfix commit from main
git cherry-pick a1b2c3d4

# Cherry-pick with traceability annotation in commit message
git cherry-pick -x a1b2c3d4

# Cherry-pick a range (commits after A up to and including B)
git cherry-pick a1b2c3d4..f5e6d7c8

# Include A itself in the range
git cherry-pick a1b2c3d4^..f5e6d7c8

# Resolve conflict during cherry-pick
# ... edit conflicted files ...
git add src/main/java/ApiClient.java
git cherry-pick --continue

# Abort if things go wrong
git cherry-pick --abort

// WHAT INTERVIEWERS LOOK FOR

Understanding that cherry-pick copies the diff (new SHA), not the commit itself. The -x traceability flag. Range syntax with the exclusive-A gotcha. When NOT to use it (large feature branches).

// COMMON PITFALL

Cherry-picking a commit that depends on earlier commits not present on the target branch, causing unexpected compile/test failures that are hard to diagnose.