If you’ve ever worked on multiple branches in Git, you’ve likely run into a situation where you wanted to copy a commit from one branch onto another, without merging the whole branch. Enter git cherry-pick
—one of Git’s most powerful, yet underused, commands. In this article, I’ll walk you through what cherry-pick
does, how to use it effectively, and tips to avoid common pitfalls.
What Is Git Cherry-Pick?
git cherry-pick
allows you to apply the changes introduced by an existing commit onto your current branch. Unlike merging or rebasing—which bring over all changes from another branch—cherry-pick is precise: it lets you select just the commit(s) you need.
Typical use cases include fixing a bug in one branch and quickly bringing that fix to another, or sharing feature work between branches without merging unrelated changes.
Basic Usage
Suppose you’re on the develop
branch, but there’s a commit on feature/login
that you need. First, get the commit hash with:
git log feature/login
Then run:
git checkout develop
git cherry-pick <commit-hash>
That’s it! The commit is now applied to develop
. Cherry-pick creates a new commit with the same changes (but a new hash).
Cherry-Picking Multiple Commits
You can cherry-pick a range of commits:
git cherry-pick <start-commit>^..<end-commit>
This will apply all commits from <start-commit>
up to, and including, <end-commit>
.
Resolving Conflicts
Cherry-picking can trigger conflicts, just like merging. If that happens:
-
Resolve conflicts in your editor.
-
Run:
git add <file> git cherry-pick --continue
-
If you need to abort:
git cherry-pick --abort
Tips and Best Practices
- Write clear commit messages: Cherry-picked commits will have a new commit hash, but it’s good practice to annotate with the original commit reference if useful.
- Avoid cherry-picking merge commits unless necessary: It can get complicated (use
--mainline
if you must). - Use with caution in shared history: Cherry-picking can make history harder to read if overused.
Conclusion
git cherry-pick
isn’t just for emergencies—it’s a powerful part of your Git toolbox for precisely moving changes across branches. Whether you’re hotfixing, backporting, or just reusing great code, mastering cherry-pick makes you a more flexible and efficient developer.
Happy coding!
— Joe Git
Leave a Reply