Git Cherry-pick

Safaetul Ahasan
DevOps.dev
Published in
2 min readMar 31, 2023

--

Cherry picking means to choose a commit from one branch and apply it onto another branch.

Here is an example of how to cherry-pick a commit:

  1. Make sure you are on the branch where you wants to add a new commit.(where you wants to add a new commit)
git switch main_branch

2. Use git log to find the commit hash of the commit:

git log

or

git log --oneline //for get 7 digits hash commit

or

//see commits to a specific branch(which branch commit you want to copy)
git log --oneline feature_branch

Copy the hash commit thats you want to cherry-pick

3. Execute the following command:


git cherry-pick <commit-hash>

or

git cherry-pick feature_branch~2

How to cherry-pick multiple commits:

If you want to pick all the commits from commit A to c(where A is older than c) run:

git log --oneline  //get 7 digits hash commit

git cherry-pick A^..C //pick all the commits from A to C (including A)

If you need to exclude the first commit (Commit A in our case)

//If you want to ignore A itself
git cherry-pick A..C //pick all the commits from B to C (exclude A)

4. Push up this branch like normal:

git push origin main_branch

If conflicts:

After solved conflicts, add the files to your staging area and continue the cherry-pick process.

git add .

git cherry-pick --continue

Why Need Cherry-Pick

Case 1(Fixed some bugs):

Suppose you are working on feature_branch. In this branch you solved 1 bug But Urgently you need to Live this bug on master branch.

Solution:

In this case, you can copy the bug fix commit from feature_branch and apply/past it onto master branch by Cherry-Pick.

Case 2 (Accidentally commit wrong branch):

Suppose you have accidentally committed something important to the wrong branch.

Solution:

Use the cherry-pick command. You can copy the commit in the correct branch. And then use git reset to undo this commit from the wrong branch.

Case 3 (Copy specific feature to another branch for published):

Suppose you are working with a team of developers on a medium to large-sized project. Some changes/feature proposed by another team member and you want to apply some of them to your main project, not all.

You don’t want to merge a whole branch into another branch. You only need to pick one or two specific commits. To pick some changes into your main project branch from other branches is called cherry-picking.

--

--