Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to cherry pick in Git

📅 2017-Sep-04 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cherry pick, git ⬩ 📚 Archive

Cherry picking in Git allows you to pick a specific commit and replay the changes done in that single commit on your current commit. This is different from a merge, where Git tries to replay the changes of all the commits from the other branch. Even if you specified a commit for a merge, Git will try to fuse the branch of which that commit is head to your current branch. After a merge, the two branches are fused in the DAG.

In contrast, a cherry pick replays changes on your current workspace. After you cherry pick a commit and replay it on your current commit, you will see that there is no branch being merged to your commit in the DAG. There will just be one or more new commits.

$ git cherry-pick 123456
$ git cherry-pick some_branch
$ git cherry-pick 123456 some_branch some_tag

The above command will result in 3 new commits on your current branch.

Cherry-picking changes all the files that were changed in a commit. If you need to pick only the changes from a specific file in a specific commit, we need to be a bit more clever.

First, we get the diff of the changes on a specific file in a specific commit:

$ git show 123456 -- foo/bar.cpp

We can then pipe this diff to be applied as a patch on our current workspace:

$ git show 123456 -- foo/bar.cpp | git apply -

Tried with: Git 2.7.4 and Ubuntu 16.04


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧