Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

The problem

So, what happened is, I was working on a branch called featureA. Now, I created this branch off another branch called featureX. The 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.

The 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 featureA branch.

The solution is to create a new branch, let’s say featureB of off main, and have all the changes of the featureA(minus 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.

The git cherry-pick command

The problem I mentioned previously can easily be solved by using git cherry-pick.

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 3e089012942f3a71330018e127fa84e2212b297e) from featureA which I want on the featureB branch.

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 featureB branch.

From here on, you push this commit to the remote counterpart of this branch leaving all the unnecessary changes (like I discussed previously)!

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?