DEV Community

Cover image for Pick a commit from another branch to the current branch (cherry-pick)
Deshan Madurajith
Deshan Madurajith

Posted on

Pick a commit from another branch to the current branch (cherry-pick)

When to use cherry-pick

  • Always try to not to use cherry-pick because it can make a duplicate commit.
  • If you have already committed something on another branch, you can pick it and merge it with your working branch. Example: you may need a hotfix commit from another branch.
  • Restoring lost comments. Sometimes a pull request might get closed without merging. But you can see those commit in the git log. So you can cherry-pick them

Alt Text

Steps

1. Get the hash of the required commit

Checkout to the branch that has the required commit. Then get git hash of that commit by using CLI or Github site



git log --oneline 
git reflog


Enter fullscreen mode Exit fullscreen mode

or you can view your git as a graph



git log --graph --oneline --all


Enter fullscreen mode Exit fullscreen mode

Alt Text

2. Cherry-pick the commit

Checkout to the brach that you want to add the commit. Enter the following command.
git cherry-pick commit-id. example:



git cherry-pick c67a4b7


Enter fullscreen mode Exit fullscreen mode

if you want to add only the content without commit. You can add --no-commit



git cherry-pick c67a4b7 --no-commit


Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
molleer profile image
David Möller

If you cherry pick with the --no-commit flag, does that mean you take credit for those lines of code when you create your commit?