0
0
Gitdevops~7 mins

Cherry-picking multiple commits in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to take specific changes from one branch and apply them to another without merging everything. Cherry-picking multiple commits lets you copy those exact changes one by one to your current branch.
When you fixed bugs in a feature branch and want to apply only those fixes to the main branch without merging unfinished features.
When you want to bring specific improvements from a development branch to a release branch.
When you accidentally committed changes to the wrong branch and want to move them to the correct one.
When you want to apply a set of commits from a colleague's branch without merging their entire work.
When you want to selectively update your branch with important commits from another branch.
Commands
Switch to the branch where you want to apply the commits.
Terminal
git checkout main
Expected OutputExpected
Switched to branch 'main'
Apply the changes from the three commits with hashes abc1234, def5678, and 9ab0cde to the current branch one by one.
Terminal
git cherry-pick abc1234 def5678 9ab0cde
Expected OutputExpected
[main 1a2b3c4] Commit message for abc1234 Author: Author Name <author@example.com> Date: Thu Apr 25 10:00:00 2024 +0000 Commit message for abc1234 [main 2b3c4d5] Commit message for def5678 Author: Author Name <author@example.com> Date: Thu Apr 25 11:00:00 2024 +0000 Commit message for def5678 [main 3c4d5e6] Commit message for 9ab0cde Author: Author Name <author@example.com> Date: Thu Apr 25 12:00:00 2024 +0000 Commit message for 9ab0cde
Verify that the last three commits on the current branch are the cherry-picked commits.
Terminal
git log --oneline -3
Expected OutputExpected
3c4d5e6 Commit message for 9ab0cde 2b3c4d5 Commit message for def5678 1a2b3c4 Commit message for abc1234
Key Concept

If you remember nothing else from this pattern, remember: cherry-picking copies specific commits from one branch to another without merging the whole branch.

Common Mistakes
Trying to cherry-pick commits without switching to the target branch first.
The commits will be applied to the wrong branch, causing confusion and possible conflicts.
Always switch to the branch where you want the commits before running git cherry-pick.
Using incorrect or partial commit hashes in the cherry-pick command.
Git will fail to find the commits and show an error.
Use full or unique abbreviated commit hashes exactly as shown by git log.
Cherry-picking commits that depend on other commits not included.
This can cause conflicts or broken code because dependencies are missing.
Ensure all dependent commits are cherry-picked together or in the correct order.
Summary
Switch to the branch where you want to apply commits using git checkout.
Use git cherry-pick followed by multiple commit hashes to apply those commits one by one.
Verify the commits applied correctly with git log --oneline.