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 (10)
Thanks! Just what I needed this morning.
Happy it solved your problem.
you are a life saver. Thanks
Glad the post could help.
It works like a magic !!!
thanks
Happy could help.
Great. Maybe cherry-pick command is used behind the scene somehow to manage merging.π
Thanks man. Yea, could be, not yet explored git that much...
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.
It gave me an warning after I tried to pull from main:
You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).
Please, commit your changes before you merge.