Sometimes you might need to apply changes that you have done on one branch and copy them to another. This can be simply done by merging that branch to the current branch that you need the changes applied to. But what if you want to select and apply certain commits only?

Git provides you a method called cherry-pick where you can select certain commits from one branch and apply it to another. You can copy a single commit or a range of commits with cherry pick. Let’s look at a simple example.

I have a repository with several branches and I need to copy a commit in develop branch to master branch

Step 1 — We have to copy the commit hash of the commit that should be copied from develop branch. ba2d88806cb34da34fc8f329938f98b1aafe6de5. You can do this by typing the git log command.

Step 2 — Checkout to the master branch and cherry pick the commit with the copied commit hash. Note that you don’t need to copy the whole commit Hash every time. Commit Hash is long enough if it’s unique

$ git checkout master
$ git cherry-pick ba2d88806cb34da34fc8f329938f98b1aafe6de5

Now you have successfully copied the commit from develop branch to master. Let’s see more options git cherry-pick offers.

Cherrypick and change commit message and author

Sometimes when you have to copy a commit, you might want to change the original commit message or author.

$ git cherry-pick ba2d88806cb34da34fc8f329938f98b1aafe6de5#1 Change commit message only, in one line
$ git commit --amend -m “PR-2 Fix”

#2 Change both author and commit message
#This will open up git interactive shell to amend the commit message
$ git commit --amend --author=”Raveen Perera <harith9127@gmail.com>”

We can also cherry pick our commit while amending the commit message in one line. This will not amend the commit author.

$ git cherry-pick ba2d88806cb34da34 --edit

( --edit option will open the interactive git shell for you to amend the commit message)

This might probably be the safest way to cherry-pick if you are not sure about the changes that will be copied. Using “no-commit” option, git will do the changes done by the commit in your working tree and stage them without committing. You can then check the changes and do a new commit to git, if everything is OK.

$ git cherry-pick ba2d88806cb34da34fc8 --no-commit

Merging is preferred over cherry-picking in developer teams. Only do cherry picking when merging is not an option.

Cherry picking can be a very powerful tool. But with great power comes great responsibility. So be careful when you copy and amend commits with cherry picking.

Happy Coding!

A Software Engineer by profession. A WildLife enthusiast. Loves the piano