Before we dive into cherry picking in Git, let’s do a quick refresher on commits. A commit is a snapshot of your Git repository at one point in time, with each commit cumulatively forming your repo history.
In Git, the cherry pick command takes changes from a target commit and places them on the HEAD of the currently checked out branch.
From here, you can either continue working with these changes in your working directory or you can immediately commit the changes onto the new branch.
The cherry pick command can be helpful if you accidentally make a commit to the wrong branch. Cherry picking allows you to get those changes onto the correct branch without redoing any work.
What happens to the commit after it’s been cherry picked onto the new branch? From here, you can either continue working with the changes before committing, or you can immediately commit the changes onto the target branch.
Cherry picking is one method of moving a commit from one branch to another in Git. But be warned! Use the cherry pick command sparingly as overusing it can lead to duplicate commits and a messy repo history.
Another method for moving a commit to another branch in Git—which may be preferred to cherry pick in order to preserve commit history—is a merge.
Let’s take a look at how the cherry pick action works using a graphical user interface for Git, like GitKraken.
In this cherry pick example, let’s say you have one branch—feature-A—checked out, and you commit your changes to said branch using the commit panel.
Drat! You just realized the commit should have been made to a different branch: feature-B. Rather than going back to redo your work, you’re going to cherry pick the commit instead.
To cherry pick in GitKraken, double click your target branch—in this case feature-B—to check it out. Next, right-click the target commit from the feature-A branch; this will open a context menu. From here, you can select Cherry pick commit.
Now, you have two options. You can immediately commit the changes to the feature-B branch, or you can keep working on them. If you choose the latter, GitKraken will add the changes to your working directory as part of the WIP node.
You’re not done yet! To ensure you keep a clean repo history, let’s go back and checkout the feature-A branch and do a hard reset on the parent commit. This will remove the duplicate commit from the feature-A branch.
The GitKraken Git client makes Git faster and more intuitive with its graphical user interface.