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:
dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master] \ 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
git cherry-pick. In this case,
62ecb3 is the cherry and you want to pick it!
git checkout master git cherry-pick 62ecb3
62ecb3 is now applied to the master branch and commited (as a new commit) in
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
The flow is to first create a new branch from
feature at the last commit you want, in this case
git checkout -b newbranch 62ecb3
Next up, you rebase the
--onto master. The
76cada^ indicates that you want to start from that specific commit.
git rebase --onto master 76cada^
The result is that commits
62ecb3 are applied to
Want to keep reading and learn more? I've got you
covered with a hand picked selection of awesome books.