BudiBadu Logo
Samplebadu

Git by Example: Cherry-Pick Commits

2.43.0

Learn how to apply specific commits from one branch to another without merging the entire branch. This is useful for hotfixes and backporting changes.

Code

# 1. Identify the commit hash you want to copy
git log --oneline feature-branch

# Output:
# 4d5e6f Fix critical bug in payment
# 1a2b3c Add new button style

# 2. Cherry-pick the specific commit to your current branch
git cherry-pick 4d5e6f

# Output:
# [main 7g8h9i] Fix critical bug in payment
#  Date: Mon Oct 2 14:00:00 2023 -0700
#  1 file changed, 5 insertions(+)

# 3. Cherry-pick multiple commits
git cherry-pick 4d5e6f 1a2b3c

Explanation

The git cherry-pick command allows you to select an arbitrary commit from one branch and apply it to another. Unlike git merge, which brings in the entire history of a branch up to a certain point, cherry-picking grabs only the changes introduced by a single commit and replays them on your current branch.

This is incredibly useful for "hotfixes". Imagine you fixed a critical bug on your development branch, but you need that fix immediately on your production branch without releasing all the other unfinished features you're working on. You can simply cherry-pick the bug-fix commit onto the production branch.

Note that cherry-picking creates a new commit with a new hash, even though the changes are the same. This can sometimes lead to duplicate commits if you later merge the branches, so use it judiciously.

  • Applies a specific commit to current branch
  • Does not merge the whole branch
  • Creates a new commit with a new hash
  • Ideal for hotfixes and backporting

Code Breakdown

2
First, you need to find the unique SHA-1 hash of the commit you want to copy.
9
The core command. It takes the changes from commit 4d5e6f and applies them to your current HEAD as a new commit.
17
You can also pass a list of commit hashes to cherry-pick multiple commits in one go.