Cherry Pick
Learn to selectively apply commits to other branches.
We'll cover the following
Cherry picking is reapplying changes of a selected commit into the current HEAD
.
It’s like git revert
, but the changes apply as is.
It’s often used when we want to apply a patch from a branch into the other branch, where merging or rebasing isn’t preferred.
How to use git cherry-pick
Let’s assume there’s a product with both versions 2.x and 3.x in active development. Assume that the team is actively working on 3.x and is maintaining 2.x with the latest security patch.
The developer team updates a security patch on 3.x for a component that’s shared between both versions. We want to apply the same patch to version 2.x as well. Since the branches for versions 2.x and 3.x are different, merging them isn’t possible. We can apply the patch to version 2.x by using git cherry-pick
.
We create a security patch as a commit in branch v3
. We want to apply this commit on v2
.
We use git log
to find out the hash of the commit. Let’s assume it’s a1b2c3d4
.
We check out the branch of version 2.x:
$ git checkout v2
Then, we use git cherry-pick
to apply the patch onto the current branch, which is v2
.
$ git cherry-pick a1b2c3d4.
This command creates a new commit on v2
, with the content and message precisely the same as a1b2c3d4
. It’s a clone of a1b2c3d4
but applied to a different branch, at a different place.
Get hands-on with 1400+ tech skills courses.