Reading time: 58 seconds
Recently I ran into a problem on a project where I was working on the wrong branch and committed changes. Those commits were supposed to go elsewhere and I now I need to get them into the correct branch!
There are a few options to solve this:
Merge the incorrect branch into the correct branch. But I don’t want to that because there are items in the incorrect branch that I don’t want. So, that’s out.
Recreate those changes in my working branch and just go on with my day. But that’s a waste of my time and I’m adamantly against redoing work!
Create a patch and then apply that patch to the new branch.
All solid options but there’s still something better:
$ git cherry-pick
Let’s review where we’re at and then how to solve the problem using
I created a new commit in my repository, in the branch called
some_other_feature. But that’s the wrong branch!
$ git branch develop master my_new_feature * some_other_feature stage
The new commit should be on the
my_new_feature branch. I could merge the branches but the
some_other_feature branch contains commits and changes that I don’t want in the other branch (they are not ready for merging into any upstream branches, like
Here’s the commit I need to get into
commit ec485b624e85b2cad930cf8b7c383a134748b057 Author: Ryan Irelan <email@example.com> Date: Fri Aug 19 10:44:47 2016 -0500 new contact page
The syntax of git-cherry-pick is this:
$ git cherry-pick [commit hash]
The first step is fetch the commit hash for the commits we want to cherry-pick. We can do that using
git-log and then copying the hash (in full or just the last 7 characters will work) to our clipboard.
Next, we need to be on the branch where we want the changes to be (our destination branch).
$ git checkout my_new_feature
Now we can run the
git-cherry-pick command and apply the commit to our destination branch.
$ git cherry-pick ec485b624e85b2cad930cf8b7c383a134748b057
This will return something like this:
[my_new_feature 1bf8955] new contact page Date: Fri Aug 19 10:44:47 2016 -0500 1 file changed, 1 insertion(+) create mode 100644 contact.html
If we look at our log for this branch, we now see our commit:
$ git log commit 1bf8955d5e6ca71633cc57971379e86b9de41916 Author: Ryan Irelan <firstname.lastname@example.org> Date: Fri Aug 19 10:44:47 2016 -0500 new contact page
What’s happening when we run
With the problem solved, we are ready to move on with our development work!