Skip to content
DeveloperMemos

A Short Guide to Git Cherry-Pick

Git, Version Control, Cherry-Pick1 min read

Git is a powerful version control system that allows developers to manage and track changes in their projects. One useful feature of Git is git cherry-pick, which enables you to select specific commits from one branch and apply them to another branch. This guide will walk you through the process of using git cherry-pick effectively, along with examples to illustrate its usage.

Prerequisites

Before getting started, please ensure that you have Git installed on your machine and have a basic understanding of Git concepts such as branches and commits.

How to Use git cherry-pick

To use git cherry-pick, follow these steps:

  1. Switch to the target branch where you want to apply the selected commit(s).
1git checkout <target-branch>
  1. Retrieve the commit hash of the commit you wish to cherry-pick. You can find the commit hash using git log or other Git visualization tools.
1git log
  1. Execute the cherry-pick command with the commit hash.
1git cherry-pick <commit-hash>
  1. Git will attempt to apply the selected commit to the current branch. In case of conflicts, you will need to resolve them manually.

  2. After resolving any conflicts, commit the changes.

1git commit

Congratulations! You have successfully cherry-picked a commit into your target branch. Repeat the above steps for each additional commit you want to apply.

Examples

Let's explore some examples to gain a better understanding of how git cherry-pick works.

Example 1: Cherry-picking a Single Commit

Suppose you have two branches, feature-branch and main-branch, where feature-branch contains a commit with a bug fix that you want to apply to main-branch.

  1. Switch to the main-branch.
1git checkout main-branch
  1. Retrieve the commit hash of the bug fix commit from the feature-branch.
1git log feature-branch
  1. Cherry-pick the commit into the main-branch.
1git cherry-pick <commit-hash>
  1. Resolve any conflicts if they occur and commit the changes.
1git commit

You have successfully cherry-picked the bug fix commit from feature-branch to main-branch.

Example 2: Cherry-picking Multiple Commits

In this scenario, let's say you need to apply multiple commits from one branch to another.

  1. Switch to the target branch.
1git checkout target-branch
  1. Retrieve the commit hashes of the desired commits.
1git log source-branch
  1. Execute the cherry-pick command for each commit.
1git cherry-pick <commit-hash-1>
2git cherry-pick <commit-hash-2>
  1. Resolve any conflicts that arise and commit the changes.
1git commit

By following these steps, you can selectively cherry-pick multiple commits from one branch to another.