Imagine a Scenario, when a developer mistakenly commits changes to the wrong branch not realizing their current branch, to correct the mistake developer needs to execute a different series of commands. This includes checking the commit details with ‘git show’, saving the commit, switching to the correct branch (e.g., main branch), applying a patch, and committing with the same message. The Git cherry pick command enables performing the entire above process with a single command. Let’s discuss it in more detail.
What is Cherry-Pick in Git?
Cherry-Pick is a process of selecting a specific commit from one branch and applying its changes to another branch. This differs from alternative methods like merging and rebasing, where the usual practice involves integrating multiple commits between branches.
The syntax of cherry-pick command is as follows:
git cherry-pick <commit-hash>
Reasons to choose the command
There are so many reasons to choose a git cherry-pick command. Let’s understand with the example, suppose a large team of developers working together. One of the team members suggests some project modification but you are interested in applying only some of those changes in your project. Handling changes across multiple Git branches can become complicated, especially when you prefer not to merge entire branches. At this time the targeted selection of particular commits for integration into your main project branch is referred to as cherry-picking.
Another reasons is Cherry-picking can help keep your commit history clean by avoiding unnecessary merges of entire branches. This is especially valuable where Teams prefer a linear, focused history in projects,
How to use Cherry-pick in Git?
1 : you just have to specify the unique SHA identifier of the commit you wish to include in your current working branch.
$ git cherry-pick <commit-hash>
This will commit the specified changes to your current checked-out branch.
2 : If you want to make additional changes, you can also command Git to include the modifications from the commit in your working directory.
$ git cherry-pick <commit-hash> --no-commit