Failure is inevitable


Git Tips & Tricks, Part 7–Move Commits Between Branches with ‘cherry-pick’

One of my favorite git features is the ability to grab a commit and re-apply it on a different branch.  In this post, I’ll show you how to do this with the ‘cherry-pick’ command.

My team and I use a fairly standard git workflow.  Our master branch contains work that is actively under development.  A stable “release” branch is used for publishing to production.  When a bug is found, we may need to apply the fix to to both master and release.  We could apply the fix to release first, then merge that back in to master, but that violates our practice (new work should happen in to master!)   Of course we can’t just merge master into release since there may be other commits on master that aren’t ready to go to release yet:


This situation is a beast to handle with Subversion, but it’s trivial with git.  I simply find the commit hash of the commit I want to move, then do the following:

git checkout master
#find the commit hash from master
git checkout release
git cherry-pick 153438e #This is the commit hash you found above

That applies my commit from master onto release without taking changes from other commits with it:


If you want to apply multiple commits, you can do a “cherry-pick” with multiple commit hashes.  You can also pass the “-n” flag to cherry-pick, which will apply and stage the changes from the target commit without actually creating a new commit.  This gives you the chance to make additional changes before committing:

git checkout master
#find the commit hashes
git checkout release
git cherry-pick -n 153438e  #Commit 1
git cherry-pick -n 253438e  #Commit 2
git cherry-pick -n 353438e  #Commit 3
git commit -m "Your combined commit message here."

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications. He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight, where he publishes courses on everything from web applications to testing!

blog comments powered by Disqus