Cherry-Picking Commits
You'll learn how to selectively apply individual commits from one branch to another without merging entire branches.
What is Cherry-Picking?
Cherry-picking in Git is like plucking specific apples from one basket and placing them into another—you're not dumping the entire basket, just selecting the ones you want. When you cherry-pick a commit, Git creates a new commit on your current branch with the same changes as the original, but with a different commit hash.
This is useful when you need a specific bug fix or feature from another branch without merging everything that branch contains.
When to Use Cherry-Picking
Cherry-picking shines when:
- A critical bug fix was committed to the wrong branch
- You need one feature from a development branch in production immediately
- You want to backport a specific fix to an older release branch
- You're cleaning up messy branch history selectively
Basic Cherry-Pick Syntax
git cherry-pick <commit-hash>
This applies the changes from <commit-hash> to your current branch. You can find commit hashes using git log.
To cherry-pick multiple commits:
git cherry-pick <hash1> <hash2> <hash3>
Or a range:
git cherry-pick <start-hash>..<end-hash>
Handling Conflicts
Like merging, cherry-picking can cause conflicts if the same code was modified differently. Resolve conflicts the same way you learned in earlier lessons, then use git cherry-pick --continue to finish.
To abort a problematic cherry-pick: git cherry-pick --abort
Key Takeaway: Cherry-picking lets you surgically apply specific commits across branches without full merges, creating duplicate commits with new hashes—use it sparingly to avoid confusing branch histories.