0
0
Gitdevops~5 mins

git cherry-pick a single commit - Commands & Configuration

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. Git cherry-pick lets you copy a single commit from one branch to your current branch.
When you fixed a bug in a feature branch and want to apply just that fix to the main branch without merging all changes.
When you want to add a specific feature or update from another branch without bringing in unrelated commits.
When you accidentally committed a change to the wrong branch and want to move it to the correct one.
When you want to test a single commit from another branch in your current branch before merging.
When you want to backport a fix from the latest version branch to an older release branch.
Commands
Switch to the branch where you want to apply the commit. Here, we switch to the main branch.
Terminal
git checkout main
Expected OutputExpected
Switched to branch 'main'
Apply the single commit with hash 3a1b2c4 from another branch onto 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 -1
Expected OutputExpected
commit 9f8e7d6b1234567890abcdef1234567890abcdef Author: Jane Doe <jane@example.com> Date: Thu Apr 25 10:00:00 2024 +0000 Fix typo in README
Key Concept

If you remember nothing else from this pattern, remember: git cherry-pick copies a single commit from another branch onto your current branch without merging all changes.

Common Mistakes
Trying to cherry-pick a commit without switching to the target branch first.
The commit will be applied to the wrong branch, causing confusion and potential conflicts.
Always switch to the branch where you want the commit before running git cherry-pick.
Using an incorrect or incomplete commit hash.
Git will return an error saying it cannot find the commit.
Use the full or unique prefix of the commit hash exactly as shown by git log.
Ignoring conflicts that occur during cherry-pick.
Conflicts stop the cherry-pick process and must be resolved before continuing.
Resolve conflicts manually, then run git cherry-pick --continue to finish.
Summary
Switch to the branch where you want to add the commit using git checkout.
Run git cherry-pick with the commit hash to copy that single commit.
Verify the commit was added by checking the latest commit with git log -1.