0
0
Gitdevops~5 mins

Why cherry-pick is useful in Git - Why It Works

Choose your learning style9 modes available
Introduction
Sometimes you want to take a specific change from one branch and add it to another without merging everything. Cherry-pick lets you copy just that one change easily.
When you fixed a bug in a feature branch and want to apply the fix to the main branch without merging all feature changes
When you want to add a small improvement from one branch to another without bringing unrelated commits
When you accidentally committed a change to the wrong branch and want to move it to the correct branch
When you want to test a specific commit from another branch in your current branch
When you want to share a single commit with a teammate without sharing the whole branch
Commands
Switch to the main branch where you want to apply the specific change.
Terminal
git checkout main
Expected OutputExpected
No output (command runs silently)
Copy the commit with ID 3a1b2c4 from another branch and apply it to the current branch.
Terminal
git cherry-pick 3a1b2c4
Expected OutputExpected
[main 9f8e7d6] Fix typo in README Author: Jane Doe <jane@example.com> Date: Thu Apr 25 10:00:00 2024 +0000 README typo fixed
Check the latest commit on the current branch to confirm the cherry-pick was successful.
Terminal
git log --oneline -1
Expected OutputExpected
9f8e7d6 Fix typo in README
Key Concept

If you remember nothing else from this pattern, remember: cherry-pick lets you copy a single commit from one branch to another without merging all changes.

Common Mistakes
Trying to cherry-pick a commit that causes conflicts without resolving them
The cherry-pick will stop and not complete until conflicts are fixed, leaving the branch in a conflicted state
Manually fix the conflicts shown, then run 'git cherry-pick --continue' to finish
Cherry-picking commits that depend on previous commits not included
The cherry-picked commit may not work correctly if it relies on earlier changes missing in the target branch
Also cherry-pick the dependent commits or merge the branches instead
Cherry-picking commits without checking out the correct target branch first
The commit will be applied to the wrong branch, causing confusion and possible errors
Always switch to the branch where you want the commit before running cherry-pick
Summary
Use 'git checkout' to switch to the branch where you want to apply a specific commit.
Run 'git cherry-pick <commit-id>' to copy that commit to your current branch.
Verify the commit was added with 'git log --oneline -1'.