0
0
GitHow-ToBeginner · 3 min read

How to Cherry Pick Commit in Git: Simple Guide

Use the git cherry-pick <commit-hash> command to apply a specific commit from another branch onto your current branch. This copies the changes from that commit without merging the entire branch.
📐

Syntax

The basic syntax of cherry-pick is:

  • git cherry-pick <commit-hash>: Applies the changes from the specified commit to your current branch.
  • <commit-hash> is the unique identifier of the commit you want to copy.
bash
git cherry-pick <commit-hash>
💻

Example

This example shows how to cherry-pick a commit from the feature branch to the main branch.

First, switch to the main branch, then cherry-pick the commit by its hash.

bash
git checkout main
# Suppose the commit hash to cherry-pick is abc1234
git cherry-pick abc1234
Output
Finished one cherry-pick. [main 9fceb02] Commit message from abc1234 1 file changed, 2 insertions(+), 1 deletion(-)
⚠️

Common Pitfalls

Common mistakes when using git cherry-pick include:

  • Trying to cherry-pick a commit that causes conflicts without resolving them.
  • Cherry-picking commits that depend on other commits not included, causing broken code.
  • Not switching to the correct branch before cherry-picking.

Always check the commit dependencies and resolve conflicts carefully.

bash
git cherry-pick abc1234
# If conflict occurs, Git will pause cherry-pick
# Resolve conflicts in files, then run:
git add <resolved-files>
git cherry-pick --continue
📊

Quick Reference

CommandDescription
git cherry-pick Apply a single commit to current branch
git cherry-pick Apply multiple commits in order
git cherry-pick --continueContinue after resolving conflicts
git cherry-pick --abortCancel cherry-pick and revert changes

Key Takeaways

Use git cherry-pick to copy specific commits without merging whole branches.
Always be on the target branch before running cherry-pick.
Resolve conflicts carefully if they appear during cherry-pick.
Check commit dependencies to avoid broken code after cherry-pick.
Use --continue or --abort to manage conflicts during cherry-pick.