Learn Git cherry-pick

🌐

This post has been translated by DeepL . Please let us know if there are any mistranslations!

git cherry-pickis a command that pulls a specific commit into the current branch. As the name suggests, it's easy to understand that it's the act of picking a specific commit (cherry) from a bunch of commits.

Image.png

How it works

Every commit has a unique ID, a hash value, which can be used to pull a specific commit.

Image.png

The basic command is

git cherry-pick <commit-hash>

Let's import the history of that commit into main without doing a merge.

The current log in the main branch looks like this

Image.png

Image.png

Image.png

The committed changes have been imported into the main branch, and the HEAD now points to the commit we cherry-picked.

You can import multiple commits, or you can specify a range.

# Importing multiple commits
git cherry-pick <commit-hash1> <commit-hash2>

# Get a range
git cherry-pick <start-commit>..<end-commit>

Key options

  • -edit or -e: Allows you to edit the commit message.
  • -no-commit or -n: Adds changes to the staging area only and does not commit them.
  • -signoff or -s: Add a signature to the commit message.
  • -x: Add the original commit hash to the commit message.

When to use it?

  • Apply bug fixes

    • When you need to quickly apply a bug found in a particular branch to other branches.
    • Example: Applying an urgent bug fix from the production branch to the development branch
  • Migrating a specific feature

    • When you need to bring only part of a feature developed in one branch to another branch.
    • Example: Integrating a successful feature from an experimental branch into the main development line
  • Managing releases

    • Selectively pulling only the changes that should be included in a particular release.
    • Example: Selectively applying only features that will be included in the next version release

Beware of conflicts

Since cherry pick is still taking commits and merging them together, conflicts can occur at any time.

If you encounter a conflict, you can resolve it and continue with the command below.

git cherry-pick --continue

Additional options:

  • Abort cherry-pick: If resolving the conflict is complicated or you want to cancel cherry-pick, you can run
git cherry-pick --abort

This command reverts to the state before cherry-pick started.

  • Leave conflicts in place and move on to the next commit: If you are cherry-picking multiple commits, you can leave the current conflicts in place and move on to the next commit.
git cherry-pick --skip
  • Enable 3-way merges: Use the -m option when cherry-picking to perform a 3-way merge. This can sometimes make conflict resolution easier.
git cherry-pick -m 1 <commit