DEV Community

Fongoh Martin T.
Fongoh Martin T.

Posted on

Copy commit from one branch to another without using git merge

So I was doing some tests in code today and had to create a test branch.

After the testing was done, I forgot to change the branch back to "master". So all reasonable code that I wrote afterwards was in the test branch. I had already committed and was about to push when I noticed I was on the wrong branch.

I asked myself how I can pick a commit from one branch and apply it to another (not merging both branches together with redundant/test code). So I remembered a command that Alangi Derick used, cherry-pick

How does git cherry pick works?

  • While on the wrong branch (the one that has the commit), do git log and copy the commit hash
  • Checkout to the correct branch which you want to apply the commit, eg git checkout master
  • Now apply the commit to the new branch, git cherry-pick <commit-hash>

You are good to go, all the changes from that commit hash will be copied from the old branch to the new branch.

Hope this helps someone out there.

May the source be with you

Top comments (9)

Collapse
 
karan_s_mittal profile image
Karan Mittal

you are a life saver. Thanks

Collapse
 
bosz profile image
Fongoh Martin T.

Glad the post could help.

Collapse
 
tfrick47 profile image
Terri Fricker

Thanks! Just what I needed this morning.

Collapse
 
bosz profile image
Fongoh Martin T.

Happy it solved your problem.

Collapse
 
pavel256 profile image
pavel-256

It works like a magic !!!
thanks

Collapse
 
bosz profile image
Fongoh Martin T.

Happy could help.

Collapse
 
esambe profile image
esambe

Great. Maybe cherry-pick command is used behind the scene somehow to manage merging.😁

Collapse
 
bosz profile image
Fongoh Martin T.

Thanks man. Yea, could be, not yet explored git that much...

Collapse
 
syedsuhaib profile image
Suhaib H Syed

I signed up at dev.to just to say thanks to you. Thank you for explaining the cherry-pick command in just the right context.