Cherry picking commits in Git
I have been using Git since the start of my career (Which spans 10 years now). I have heard about this Git’s feature called
cherry-pick every now and then but I haven’t been in a situation where I would actually use it. Until today.
So, what happened is, I was working on a branch called
featureA. Now, I created this branch off another branch called
featureX branch had some commits which haven’t been merged to the
main branch yet.
I completed my changes for the
featureA branch and committed my changes. Now, the real problem occurred.
featureA branch had commits of the
featureX branch. And this prevented me from creating a PR out of this since the
featureA doesn’t need changes of these commits. I only needed changes that I made specifically in the
The solution is to create a new branch, let’s say
featureB of off
main, and have all the changes of the
featureX). Normally, you would do this manually copy-pasting the changes to the
featureB branch. But it’s kind of boring. And that’s where git cherry-pick comes into the picture.
git cherry-pick command
The problem I mentioned previously can easily be solved by using
It’s a nice little Git command using which you can apply the changes introduced by some existing commits of a branch to another branch.
So, for instance, if I want to apply changes of the
featureA branch to the
featureB branch, all I need to do is to copy the ID of the commit (let’s say it’s
featureA which I want on the
And then check out to the
featureB branch and apply the commit like so.
$ git cherry-pick 3e089012942f3a71330018e127fa84e2212b297e
Doing so will apply all the changes from this commit to the
featureB branch by creating a brand new commit in the same branch and
HEAD will now be pointing to this commit
You can check this by using
git log like so.
As you can tell, we now have a new commit called “test cherry picking” with a brand new commit ID in the
From here on, you push this commit to the remote counterpart of this branch leaving all the unnecessary changes (like I discussed previously)!