Last updated

Cherry-Picking specific commits from another branch

I’m often asked how to merge only specific commits from another branch into the current one. The reason you’d want to do this is to merge specific changes you need now, leaving other code changes you’re not interested in right now behind.

First of all, use git log or the awesome GitX tool to see exactly which commit you want to pick. An example:

1dd2e86 - 946992	- 9143a9 - a6fd86 - 5a6057 [master]
2           \
3            76cada - 62ecb3	- b886a0 [feature]

Let’s say you’ve written some code in commit 62ecb3 of the feature branch that is very important right now. It may contain a bug fix or code that other people need to have access to now. Whatever the reason, you want to have commit 62ecb3 in the master branch right now, but not the other code you’ve written in the feature branch.

Here comes git cherry-pick. In this case, 62ecb3 is the cherry and you want to pick it!

1git checkout master
2git cherry-pick 62ecb3

That’s all. 62ecb3 is now applied to the master branch and commited (as a new commit) in master. cherry-pick behaves just like merge. If git can’t apply the changes (e.g. you get merge conflicts), git leaves you to resolve the conflicts manually and make the commit yourself.

Cherry picking a range of commits

In some cases picking one single commit is not enough. You need, let’s say three consecutive commits. cherry-pick is not the right tool for this. rebase is. From the previous example, you’d want commit 76cada and 62ecb3 in master.

The flow is to first create a new branch from feature at the last commit you want, in this case 62ecb3.

1git checkout -b newbranch 62ecb3

Next up, you rebase the newbranch commit --onto master. The 76cada^ indicates that you want to start from that specific commit.

1git rebase --onto master 76cada^

The result is that commits 76cada through 62ecb3 are applied to master.