0
0
GitHow-ToBeginner · 3 min read

How to Use Git Cherry-Pick: Simple Guide and Examples

Use git cherry-pick <commit-hash> 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 git cherry-pick is simple and includes the commit hash you want to apply. You can also cherry-pick multiple commits or a range.

  • git cherry-pick <commit-hash>: Apply one commit.
  • git cherry-pick <commit1> <commit2>: Apply multiple commits.
  • git cherry-pick <start-commit>^..<end-commit>: Apply a range of commits.
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(+)
⚠️

Common Pitfalls

Common mistakes when using git cherry-pick include:

  • Trying to cherry-pick a commit that causes conflicts without resolving them.
  • Cherry-picking merge commits without special options.
  • Not committing or aborting after conflicts.

Always resolve conflicts carefully and use git cherry-pick --abort to cancel if needed.

bash
git cherry-pick abc1234
# If conflict occurs, fix files then:
git add <fixed-files>
git cherry-pick --continue
# To cancel cherry-pick if stuck:
git cherry-pick --abort
📊

Quick Reference

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

Key Takeaways

Use git cherry-pick to copy specific commits from one branch to another without merging.
Always resolve conflicts carefully and use --continue or --abort commands as needed.
You can cherry-pick single commits, multiple commits, or a range of commits.
Cherry-picking does not change branch history except adding the picked commits.
Avoid cherry-picking merge commits unless you understand the implications.