Skip to content Skip to navigation

Cherry Picking - Small Git lesson

Small commits allow for big wins.

Something that I have been using a lot lately is GIT's cherry-pick command. I find the command very useful, and it saves me bunches of time. Here is a quick lesson on what it does and an example use case.

What is GIT cherry-pick? man page

Git cherry-pick allows you to merge a single commit from one branch into another.  To use the cherry-pick command follow these steps:

  1. Check out the branch into which you want to merge the commit. (E.g.: git checkout master)
  2. Identify the commit hash through your favorite method. You can use git log, a GUI tool such as sourcetree or tower, or if you use GitHub or BitBucket you can use their interface. In SWS we use GitHub, so I tend to use that method often. With GitHub you can find the commit hash on the commit list page or on the individual commit page itself.  See the screenshots below.
  3. Pick'em! eg: git cherry-pick 9638d99c89a92350ad2f205f47af24b81ac39a64
  4. If there is a merge conflict you will have to resolve that with your favorite merge tool, but otherwise you have now successfully pulled in the work from the other branch. 

Why would I use this?

That is a good question. Why would you cherry-pick instead of just merging one branch into the other? The short answer is that you cherry-pick when a full branch merge is not possible due to incompatible versions or simply because you do not want everything in the other branch. 

A common use case for Drupal module maintainers is when a security vulnerability has been identified and fixed in a Drupal version number and has to be applied to others. For example, if a security fix has been found in the Drupal 6 version of the stanford_events module, then that fix may apply to the Drupal 7 version. Instead of having the developer apply the change manually to the Drupal 7 version that developer can use Git cherry-pick for commit and carry on. 

How to find the commit hash on GitHub:


In SourceTree, I have found that I can select a branch from the left (single clicking so as not to switch to that branch), then from the right side I click any commit from that branch, then checkout one of the modified files by right clicking on them in the list below and selecting "Reset to Commit". Is this not the correct way to cherry pick with SourceTree?

I am not overly familiar with the Source Tree product but I did find this article on Atlassian's help forum:

I hope this helps. Thanks for the comment!

In SourceTree, the way to cherry pick is to:

1) Switch to the branch that you'd like the changes to be applied to
2) Find the commit from the other branch that you'd like to apply to this one
3) Right-click on it and choose "Cherry Pick"

The commit will be applied to your branch immediately if there are no conflicts. If there are conflicts, you can resolve those the usual way and commit when done.