Git - How to use the cherry-pick command

Get specific changes from one branch to another using the commits history and the cherry-pick command.

Git - How to use the cherry-pick command

When we are working in a project where there is more than one developer editing the code, the use of tools like Git can prevent us from having headaches managing the version control of our code.

These are the most common commands used on a daily basis:

//Clone an existing repo
git clone

//Create a new branch
git branch NewBranch

//Checkout a branch
git checkout NewBranch

//Commit pending changes
git commit

//Push pending commits to the repo
git push

Imagine that you worked on some features and you have a lot of commits but for whatever reason the client want to make a partial deployment of things that already have been tested and approved, that means "release a few commits".

For that and others, not so happy, scenarios we have the cherry-pick command that allows us to get a specific commit from a branch into another using the commit SHA.

You can access the commits history in descending order with the following command:

git log

//Result example of git log
commit bd1b (HEAD -> main, Feature2)
Author: Patricio
Date:   Wed Aug 24 12:06:03 2022
 Second commit

commit ca35 (Feature3)
Author: Patricio
Date:   Wed Aug 24 12:03:23 2022
 First commit

When you have the specific commit or commits that you need to get into your branch, you only need to be on your target branch and run the cherry pick as follows:

git checkout Feature3
git cherry-pick bd1b

//Result example of cherry-pick
[feature3 0fc3b3b] Second commit
Date: Wed Aug 24 12:36:47 2022
1 file changed, 4 insertions(+)

After the command runs you can now perform any task with the changes that you need already merged in your branch.

This is how it looks like the work of cherry pick command:

cherry pick diagram

This command is very useful on other cases like a change being committed in the wrong branch, you can checkout the correct branch an then cherry pick that commit you need.

Sé productivo. Sé extraordinario. Sé INAVANT.