DEV Community

Kenny Grant for Project Page

Posted on

How to move a commit to another branch in git

Here's a little git problem that happened to me today, which used to be quite scary when I was first learning git but is actually easy to remedy as long as you are working locally.

We've all done it - sometimes you forget you haven't created a branch yet, or worse yet you're on the wrong feature branch, and you start adding some code and make a commit. Then you realise you've committed code to the wrong feature branch or straight to master, and now it's in the wrong place.

As long as you haven't pushed your changes up to origin, this is very easy to undo. Let's say we have made a commit a1b2c3d on the branch feature-a, and we haven't yet made a feature-b branch.

So first of all we want to get our commit onto the right branch, so let's take a note of the hash want to move, and start at master:

git checkout master

Optionally (if we don't have the branch yet) we make a new branch feature-b to put it on and check it out:

git checkout -b feature-b

Then make sure you are on the right branch feature-b (may not be necessary if you just created it), and cherry pick this commit into that branch to add just that commit to feature-b:

git checkout feature-b
git cherry-pick a1b2c3d

And finally let's reset feature-a branch back to the previous commit hash (say z1b2c3d). Using git reset --hard will remove all the commit referencing the changes, and all the changes themselves, from feature-a branch, while leaving that commit on feature-b:

git checkout feature-a
git reset --hard z1b2c3d

You can do this with multiple commits too, just cherry pick several, then reset back to the last commit you want to keep. The process is the same if you have committed to local master by mistake - just cherry-pick to a branch, then reset master.

Only ever do this if you haven't pushed the commits to origin.

Top comments (9)

Collapse
 
sodjanathan profile image
nat_souljah

What if I have already sent the changes to remote

Collapse
 
hnakao profile image
hnakao

git reset --hard HEAD~X // where X is the total of commit to move back

or

git reset --hard a1b2c3d4 // simply provide the hash of the commit you want to revert back to..

and

git push origin master --force // change "master" to the branch you want to revert.

Collapse
 
haritsinh profile image
Haritsinh Gohil

I will pray for you.

Collapse
 
katonadavid profile image
Dávid Katona

Thank you! Saved my a** :)

Collapse
 
harrybawsac profile image
Harry Bawsac

Thanks so much!

Collapse
 
hisham profile image
Hisham Mubarak

Thank you. Just what I wanted :)

Collapse
 
ekimkael profile image
Ekim Kael

Guy! you just saved my life!
THANK YOU!!!!!

Collapse
 
abh31000 profile image
abh31000 • Edited

I just created an account to like this post, and say big thanks!!

Collapse
 
ajalasegun1 profile image
Segun Ajala

I signed up so i can tell you thank you