What is Git cherry-pick? How to use it🍒
Git cherry-picking refers to the process of selecting individual commits from any branch and applying them to the current HEAD branch.
Unlike git rebase and git merge, which involve taking all the commits in an entire branch, cherry-pick allows you to choose specific changes and apply them to another branch:
When You should use git cherry-pick
git cherry-pick is a handy tool but should be used sparingly, as it can result in duplicate commits.
When you cherry-pick a commit, Git creates a new commit with the same changes but a different HASH identifier, resulting in two separate commit objects containing the same code changes:
Traditional merging and rebasing are preferred to integrate commits when possible because they avoid creating duplicate commits.
Cherry-picking is best reserved for special cases where normal integration is not feasible. For example:
Undoing changes, let’s say you accidentally made a commit to the wrong branch. You can switch to the correct branch and then cherry-pick the commit to the right branch.
Applying hotfixes where a specific fix needs to be propagated quickly without merging everything from the source branch.
Taking one or more commits with shared code like a data structure from one product sub-team to another (ex: backend to frontend) for them to reuse rather than merging unrelated code from multiple components.
Using the Git Cherry-Pick Command
Now that you understand what git cherry-pick does, let's put that knowledge into practice. To demonstrate, we'll use a repository with the following branch structure:
The cherry-pick command is straightforward - just provide the commit hash you want to copy: $ git cherry-pick <commit-hash>
To find the commit hash, run:
$ git log --all --decorate --oneline --graph
Before cherry-picking, check out the target branch that you want to apply the commit to. In our example, let's work on the main branch:
$ git checkout main
Now, suppose you wish to apply commit "C5" to the main branch; execute the following command:
$ git cherry-pick C5
Replace C5 with the actual commit hash. After execution, the commit history now looks like:
Cherry Picking Multiple Commits
Cherry-picking multiple commits at once is also possible.
To pick out several commits, specify the commit hashes separated by spaces:
$ git cherry-pick C4 C6
The commits will be applied in the order specified:
Summing up!
In this short newsletter, we covered what git cherry-picking is, when you should use it, and demonstrated how to the git cherry-pick command to pick out individual commits from a different branch.
That’s all! Hope you learn something new from this newsletter. If so, please let me know by liking it. If you're new here, do subscribe to my newsletter for more threads, tips, and resources on Linux, DevOps, and sysadmin.