Home Resource Centre Git Cherry Pick Command | How To Use, Undo, Resolve Conflicts & More!

Git Cherry Pick Command | How To Use, Undo, Resolve Conflicts & More!

Git is a distributed version management system that enables concurrent work on the same codebase by numerous developers. It allows users to collaborate on projects and records changes made to files and folders over time.

In Git, commands are necessary for efficient code management, teamwork, and version control. They allow for a variety of actions, including Git branch creation for novel features or experiments, tracking changes, managing multiple versions of the code, and tracking changes. Using commands like git clone, git pull, and git push to share code, fetch the most recent changes, and merge their work back into the main repository; developers may work together invisibly with Git. One such command available is Git cherry-pick.

In git, cherry-picking refers to selecting a commit from one branch and applying it to another. This contrasts with other techniques like merge and rebase in git, which often applies numerous commits into a different branch. In this article, we will learn about Git cherry-pick in detail.

What Is Git Cherry Pick?

We can apply a specific commit from one branch to another branch using the Git command 'git cherry-pick'. This command is helpful when applying changes from one branch to another without merging the complete branch. Git updates the current branch with the changes from the provided commit when we execute the git cherry-pick command.

If there are any inconsistencies between the changes in the commit and the modifications in the current branch, Git will prompt us to fix them manually.

The Syntax For Git Cherry Pick

git cherry-pick <commit-hash>

Here, 

  • git cherry-pick: This command can be used to copy a single commit or a range of commits from one branch to another
  • <commit-hash>: The hash of the commit that we want to apply to the current branch is represented by the "commit-hash."

Git updates the current branch with the changes from the provided commit when we execute the git cherry-pick command.

Git Cherry Pick Example

Let’s see an example of the command Git Cherry-Pick. In this demonstration, we'll construct a brand-new Git sample project repository named cherrypicker and apply a bug fix from the master branch to the feature branch using the git cherry-pick command. The process of creating the repository and using the Git cherry-pick command is as follows:

  1. First, create a Git repository and add a new directory. The commands to be used are-
    $ mkdir cherrypicker
    $ cd cherrypicker
    $ git init
  2. Then, create an empty file called cherry-picking.ext and make an initial commit using the following commands-
    $ touch cherry-picking.ext
    $ git add
    $ git commit -m 'Initial commit'
  3. Next, use the $ git branch feature command to create a new branch called feature and switch to it using the $ git switch feature command.
  4. Now, create a new file called cherry-feature.ext and make a commit using the commands given below-
    $ touch cherry-feature.ext
    $ git add
    $ git commit -m 'Started feature'
  5. Next, switch to the master branch and make a bug fix to the cherry-picking.ext file. The commands used here are-
    $ git switch master
    $ echo 'Bug fix.' >> cherry-picking.ext
    $ git commit -am 'Bug fix'
  6. Identify the commit hash of the bug fix commit using the git log command (i.e., $ git log --oneline).
  7. Then, switch back to the feature branch and use git cherry-pick to apply the bug fix commit.
    $ git switch feature
    $ git cherry-pick <commit-hash>
    Then you need to Replace <commit-hash> with the hash of the bug fix commit from step 6.
  8. Finally, verify that the bug fix has been applied to the feature branch using the $ git log --oneline command. 

When To Use Git Cherry Pick Command?

As we've mentioned, the git cherry-pick command lets us apply a particular commit from one branch to another branch. Here are several scenarios in which git cherry-pick may be useful:

  • When there is a need to apply a commit that was unintentionally made to the wrong branch to the correct branch without merging the entire development branch.

  • To apply specific changes from one branch to another without merging the entire branch.
  • A problem patch that needs to be backported to an earlier version of the application.
  • To roll back a working version of the codebase.
  • When there is a need to rectify a defective build or isolate a software bug.

How To Use Git Cherry Pick?

The process to use the git cheery pick command is explained below in a step-by-step pattern. 

  1. Firstly, change/ switch to the branch where you wish to apply the commit first using the git checkout <target-branch> command.
  2. Then, run the git cherry-pick command after obtaining the commit hash of the commit object you wish to apply. Here, the command will take the form- git cherry-pick <commit-hash>.
  3. The current branch will receive the updates from the specified commit as a result of this.
  4. Next, use the git cherry-pick --continue command to carry on with the cherry-pick if there are any conflicts to be resolved manually after the cherry-picking process.
  5. You can abort the cherry-picking process by running the git cherry-pick --abort command. This will undo any changes made during the cherry-picking process.

Note: It's vital to keep in mind that if the same commit is cherry-picked more than once, git cherry-pick may result in duplicate commits. Furthermore, traditional merge or rebase techniques might be preferred over cherry-picking as the optimal method for combining changes between branches in some cases.

Git Cherry Pick For Multiple Commits

We have already discussed how to use the git cherry-pick command to pick specific changes. In this section, we will discuss the method to cherry-pick multiple commits at once using the command. Follow the steps given below to get this done-

  1. First, change/ switch to the branch where the commits should be applied using the git checkout <target-branch> command.
  2. Next, put the commit hash of each commit you want to apply after the git cherry-pick command. For example-
    git cherry-pick <commit-hash-1>
    git cherry-pick <commit-hash-2>
    git cherry-pick <commit-hash-3>
    ...
    This will update the current branch with the modifications made in each specified commit.

Git Cherry Pick For A Range Of Commits

In addition to picking multiple changes to commit, the Git cherry-pick also gives users the option to apply a range of commits. The steps to do this are as follows:

  1. Change to the branch where you wish to apply the commits. Use the command- git checkout <target-branch>.
  2. Then, run git cherry-pick with a list of commit hashes after it, i.e., git cherry-pick <start-commit-hash>..<end-commit-hash>.

This will update the current project branch with the modifications made in each commit within the specified range.

Undo Changes & Restore Lost Commits With Git Cherry Pick

It is possible to undo the changes and restore to the previous versions using Git cherry-pick features. Here is how you can get this done:

  1. First, find the commit that you want to go back to using the git reflog command. This will show any changes that altered the HEAD.
  2. Then, check out the appropriate reflog entry to reset the HEAD to this commit.
  3. There will be a new entry in the reflog whenever the HEAD is changed.

For example, suppose you accidentally deleted a commit with the hash abc123. You can use the following commands to recover the lost commit:

git reflog
# find the hash of the lost commit in the log, e.g., abc123
git cherry-pick abc123

Git Cherry Pick Example (Command Line)

The Command Line Interface (also known as CLI) in Git provides a mechanism to communicate with Git by typing text commands into a terminal or console. The primary method for executing all Git operations is the command line interface, which offers a robust and adaptable approach to dealing with Git.

Here is an example of how to use the git cherry in the command line:

First, Change to the branch where you wish to apply the commit. Then run the following command, for instance, to apply a commit to the master branch:

git checkout master

In the next step, Using the git log command, you must then locate the hash of the commit you want to apply.

git log

When you have the commit's hash, you can use the git cherry-pick command to apply it to the current branch. If the commit's hash was abc123, for instance, you would use the following command:

git cherry-pick abc123

Finally, use the git commit command to add the modifications to the current branch:

git commit

This will create a new commit with the changes from the cherry-picked commit.

What Happens When We Cherry Pick A Git Commit?

The git cherry-pick command essentially allows us to select a commit from one branch and apply it to another branch. Here is a step-by-step analysis of what happens when we git cherry-pick a commit:

  • The modifications from the cherry-picked commit are added to a new commit by Git.
  • The new commit has a new hash even though the modifications are the same as those in the old commit.
  • We must manually settle any disputes that arise throughout the cherry-picking procedure. Git will highlight the conflicts in the concerned files so that we can update them to make them go away.
  • When a commit is cherry-picked, whatever dependencies it has on previous commits are not taken into account. If necessary, we must manually make those adjustments.

Sequencer Subcommands In Git Cherry-Pick

Git cherry-pick uses a sequencer to manage the cherry-picking process. In other words, the sequencer is a script that Git uses to manage the cherry-picking process and is stored in the .git/sequencer directory. The sequencer subcommands are used to manage the process and include the following:

  • --continue: Using the data in.git/sequencer, the --continue subcommand is used to continue an operation that is already underway. It is used after resolving conflicts that arise during the cherry-pick process.
  • --skip: This subcommand helps skip the current commit and carry on with the remaining steps of the cherry-pick procedure.
  • --quit: When a cherry-pick or reverse operation fails, the --quit subcommand is used to let go of it and clear the sequencer state.

Does Git Cherry Pick Create A New Commit?

When git cherry-pick applies a specific commit from one branch to another branch, it does indeed create a new commit. The cherry-picked commit's changes and its metadata, including the author, committer, and commit message, are all precisely replicated in the new commit.

Git analyses the changes made by the provided commit and applies them to the current branch when we run git cherry-pick <commit>. It then creates a new commit with a unique commit hash that captures those changes.

The new commit created by git cherry-pick is independent of the original commit. It has its own commit hash and is considered a separate commit within the branch's history. This allows you to selectively apply specific changes from one branch to another while maintaining a clear record of the commit history.

Git Cherry Pick Conflict

Conflicts may occur when applying changes from one branch to another using git cherry-pick if the same lines of code have been modified in both branches. Let’s take a look at an example of how such a conflict might come to be and how to resolve it.

  1. First, create two branches named master and feature, respectively, with different changes to the same file.
    Code:
    $ git checkout -b master
    $ echo "This is the original text." > file.txt
    $ git add file.txt
    $ git commit -m "Add original text."
    $ git checkout -b feature
    $ echo "This is some new text." > file.txt
    $ git add file.txt
    $ git commit -m "Add new text."
  2. Then, switch back to the master branch and make a change to the same file.
    Code:
    $ git checkout master
    $ echo "This is some different text." > file.txt
    $ git add file.txt
    $ git commit -m "Add different text."
  3. Next, switch back to the feature branch and use git cherry-pick to apply the changes from the master branch.
    Code:
    $ git checkout feature
    $ git cherry-pick <commit-hash>
    Substitute the hash of the commit you want to apply for <commit-hash>.
  4. Now, resolve the conflict by opening the file and manually editing it to include the changes from both branches. Save the file and stage it.
    Code:
    $ git status
    $ vim file.txt
    $ git add file.txt
  5. Continue the cherry-pick operation with the $ git cherry-pick --continue command.
  6. Then, verify that the cherry-pick was successful and the conflict has been resolved. For this, use the $ git log --oneline command, which will show the commit history of the current branch, including the new commit created by git cherry-pick.

Git Cherry Pick vs. Git Rebase

There are two Git commands that can help us alter the commit history of a Git repository. This includes the git cherry-pick and git-rebase commands. While these commands fulfill the same purpose, there are some key differences between the two. They are:

Git Cheery Pick

  • It allows us to apply a specific commit from one branch to another.
  • It Creates a new commit with a unique hash.
  • It Can cause duplicate commits and other issues if overused.

Git Rebase

  • It allows us to change the base of your branch from one commit to another.
  • It Creates new commits and applies them to the specified base.
  • It Can lead to conflicts and duplicate commits if not used carefully.

The table given below further elaborates on the differences between git cherry-pick and rebase. 

Aspect Git Cherry Pick Git Rebase
Purpose Selectively apply specific commits from one branch to another. Incorporate changes from one branch onto another, maintaining a linear commit history.
Workflow Creates new commits for cherry-picked changes. Rewrites commit history by reapplying commits from the source branch onto the target branch.
Commit IDs Requires specifying commit IDs for cherry-picking. Applies a range of commits based on a starting commit and an ending commit.
Commit Contents Copies individual commits with their changes. Applies changes committed by commit, potentially altering commit messages and order.
Branch Relationships Can copy commits between any branches, resulting in non-linear history. Typically used to integrate feature/topic branches into the main branch, creating a linear history.
Merge Conflicts This can result in merge conflicts for each cherry-picked commit. It can cause merge conflicts during the reapplication of commits, but conflicts are resolved at the end.
Commit Hashes Cherry-picked commits have new hash IDs, as they are new commits. Rebasing creates new commit hashes for the rewritten commits.
Collaboration Suitable for picking specific changes from external branches. Suitable for local work or shared branches if collaborators are aware of the rebase.
History Clarity Preserves original commit history, even if non-linear. Produces a cleaner linear history without merging commits.
Use Cases Isolated bug fixes or specific features need to be moved. Creating a clean history before merging into a shared branch or resolving conflicts in a controlled manner.

Is Git Cherry Pick The Same As Merge?

No, git cherry-pick is not the same as git merge. While both commands allow us to manipulate the commit history of a Git repository, they have different purposes and behaviors. The table below highlights the differences between the two.

Cherry picking Merging

Cherry-picking allows us to select and apply specific commits from one branch to another.

Merging combines the entire branch history into another branch.

It enables us to choose individual commits and apply them to a different branch, regardless of the commit history. This means we can pick and choose specific changes without merging the entire branch.

Git combines the modifications from one branch (the source branch) into another branch (the destination branch) when we perform a merge. Git examines the history of commits and applies the modifications made in the source branch to the target branch, resulting in the creation of a new merge commit that symbolizes the combination of the two branches.

Cherry-picking creates new commits in the target branch, replicating the selected changes. It is useful when we want to apply specific changes from one branch to another selectively, such as applying a bug-fix scenario or a feature. It does not preserve the original structure.

Merging preserves the commit history of both branches and creates a merge commit to track the merge operation. It is typically used to combine multiple branches, such as merging a feature branch into the main branch or integrating changes from a shared branch. It preserves the original structure

Advantages and Disadvantages Of Git Cherry Pick

In this section, we will discuss some of the most important advantages and disadvantages of using Git cherry-pick.

Advantages of using Git Cherry Pick:

  1. Selective Commit Integration: Cherry picking allows you to select and integrate specific commits from one branch into another. This is particularly useful when you only need a few changes from a branch without merging the entire branch.

  2. Isolated Changes: Cherry picking lets you bring in changes as isolated commits, making it easy to understand and track the history of individual changes.

  3. Granularity: It provides a higher level of granularity compared to other integration methods like merging or rebasing. You can choose which specific commits to include in the target branch.

  4. Independence: Cherry picking doesn't require you to alter the entire commit history of the target branch. This can be advantageous when you want to keep the target branch's history mostly intact.

  5. Flexibility: You can cherry-pick changes across different branches, even if they are not directly related. This is useful for porting bug fixes or features between different branches.

Disadvantages of using Git Cherry Pick:

  1. Non-linear History: Cherry picking can result in a non-linear commit history. This might make it harder to understand the sequence of changes and their context over time.

  2. Duplicate Commits: When cherry-picking the same commit into multiple branches, you end up with duplicate commits that might have the same changes but different commit IDs.

  3. Merge Conflicts: Each cherry-picked commit can potentially introduce merge conflicts that need to be resolved manually. This can be time-consuming, especially if you're cherry-picking multiple commits.

  4. Lack of Context: Cherry-picking individual commits might lead to the loss of context if the original changes were part of a larger feature or fix. It might not capture the full scope of the changes.

  5. Integrity of the Target Branch: Cherry picking can bring in changes without considering the state of the target branch. This might lead to compatibility issues or unexpected behavior if the changes are not well-tested together.

  6. Complexity: When cherry-picking complex changes that depend on previous commits, it might be challenging to ensure that the cherry-picked commit works correctly in the new context.

Hidden Git Cherry Pick Commit

Curious developers can apply the modifications made by an existing commit to a separate branch using the Git cherry-pick command. This command is especially helpful when attempting to pinpoint a software fault or rectify a flawed build. A cherry-picked commit between two branches might, however, occasionally be hidden in the Git log by developers. The --no-merges option of the git log command can be used to achieve this.

For Example:

# Checkout the branch where you want to apply the changes
git checkout <target-branch>
# Cherry-pick the commit from the source branch
git cherry-pick <commit-hash>

To hide a cherry-picked commit in the git log between two branches, use the following command:

git log <branch1>..<branch2> --no-merges

This command will show the log between branch1 and branch2 but exclude any merge commits.

Conclusion

It is clear that developers can transfer changes from one branch to another using the Git cherry-pick command. It is helpful in isolating software bugs or fixing broken builds. To hide a cherry-picked commit in the git log between two branches, developers can use the --no-merges option with the git log command.

A commit that is being cherry-picked will become empty if it replicates a commit that is already in the current history, which will cease cherry-picking. In case of lost commits, developers can use git reflog and git cherry-pick commands to restore them. Cherry-picking is a useful command that focuses only on the changes included in the commit that implement the desired features without bringing along another commit.

Frequently Asked Questions

Q. What is a cherry-pick in git?

Cherry-picking in Git means selecting a commit from one branch and applying it to another branch. The command- git cherry-pick makes it possible to pick any Git commit by reference and add it to the current HEAD at the moment. Cherry-picking is an advanced idea and a powerful yet handy tool, like rebasing. Its primary benefit is in cases where you only want a few of the commits and don't want to merge the entire branch.

Q. What happens if there are conflicts during a git cherry-pick operation?

Git will halt a cherry-pick operation if there are any conflicts and will ask the user to fix them before continuing with the cherry-pick. The user can then use the git cherry-pick --continue command to resolve the conflicts and continue with the cherry-picking process or the git cherry-pick --abort command to terminate the cherry-pick current operation with conflicts.

Q. Can I cherry-pick a commit from a different branch?

We can cherry-pick a commit in Git from another branch. This is a helpful Git feature that enables us to apply particular changes to a separate branch by cherry-picking a commit from a different branch. However, note that it should be used with caution to prevent conflicts and duplicate commits.

Q. Is it possible to cherry-pick a merge commit?

The git cherry-pick command cannot be used to manually cherry-pick a merging commit. Git will show an error message if we try to cherry-pick a merging commit. This is because cherry-picking a merge commit would require choosing certain modifications from many branches, which can be complicated and possibly cause disputes.

Q. How can I revert a cherry-pick if I made a mistake?

The steps to revert a cherry-pick you made by mistake are as follows:

  1. Find the commit hash of the commit that you want to move back to. You can use git log or git reflog commands to find the hash.
  2. Use the git reset command to return the branch pointer to the commit prior to the cherry-pick. For example, if the commit hash is abc123 then the command is git reset --hard abc123.

The changes made by the cherry-pick will be removed after executing these steps, and the branch will now point to the commit made before the git cherry-pick.

Q. Are there any alternative approaches to Git cherry-pick?

Yes, there are alternative approaches to Git cherry-picking. They are:

  • Git Merging: This is the process of combining modifications from one branch into another completely.
  • Git Rebasing: The process of moving a branch to a new base commit is known as rebasing.
  • Git Patching: This process entails making a patch file that contains the changes introduced by a commit.

This compiles our discussion on git cherry-pick. Read the following for more interesting articles to quench your thirst for knowldege:

  1. Introduction To Git Stash | How To Use Git Stash Commands
  2. Git Submodule: Add, Remove, Pull Changes & More (With Examples)
  3. What Is GitHub? An Introduction, How-To Use It, Components & More!
  4. Strings In C++ | Functions, How To Convert & More (With Examples)
  5. What Is Bash? Features, Major Concepts, Commands, & More!
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

TAGS
Engineering Computer Science
Updated On: 6 Oct'23, 11:32 AM IST