Skip to main content

Git cherry pick examples

·2 mins

Sometimes you just need to pull one or more commits from one branch into another branch without pulling any other changes from that branch.

Git cherry-pick is a powerful command that enables arbitrary Git commits to be picked by reference and appended to the current working HEAD. Cherry picking is the act of picking a commit from a branch and applying it to another.

git cherry-pick can also be used in cases like, say a commit is accidently made to the wrong branch. You can switch to the correct branch and cherry-pick the commit to where it should belong, so you don’t have to re-create files in correct branch and copy them etc.

Simply put, cherry-pick is picking a single commit from one branch and put that commit to a different branch.

Enough talk, here are quick example of a cherry-picking.

➜  git-examples git:(main) git log --oneline

bd2de1e (HEAD -> main, origin/main, origin/HEAD, release_3) adding testfile1
6b65eee Initial commit
➜  git-examples git:(main) git checkout release_2
Switched to branch 'release_2'
➜  git-examples git:(release_2) git log --oneline

257d33f (HEAD -> release_2, origin/release_1, release_1) release_1_feature_1 commit
0ffa8e2 release_1_file commit
bd2de1e (origin/main, origin/HEAD, release_3, main) adding testfile1
6b65eee Initial commit
➜  git-examples git:(main) git checkout release_3
Switched to branch 'release_3'
➜  git-examples git:(release_3) git log --oneline

bd2de1e (HEAD -> release_3, origin/main, origin/HEAD, main) adding testfile1
6b65eee Initial commit

Now if you want to just pull commit 257d33f from the release_2 branch, you can use cherry-pick command.

➜  git-examples git:(release_3) git cherry-pick -x 257d33f
[release_3 8d9086b] release_1_feature_1 commit
 Date: Thu Nov 12 01:11:33 2020 +0000
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 release_1_feature_1
➜  git-examples git:(release_3)

Once you have cherry picked 257d33f you can verify it with git log command that changes from that commit are not in release_3 branch as well.

➜  git-examples git:(release_3) git log --oneline

8d9086b (HEAD -> release_3) release_1_feature_1 commit
bd2de1e (origin/main, origin/HEAD, main) adding testfile1
6b65eee Initial commit