Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix committing to the wrong Git branch?

Tags:

git

git-commit

I just made a perfectly good commit to the wrong branch. How do I undo the last commit in my master branch and then take those same changes and get them into my upgrade branch?

like image 484
mikewilliamson Avatar asked May 31 '10 05:05

mikewilliamson


People also ask

What happens when you commit to the wrong branch in git?

Make sure you are on the branch to which you have been committing. Use git log to check how many commits you want to roll back. Then undo the commits with git reset HEAD~N where “N” is the number of commits you want to undo. Then create a new branch and check it out in one go and add and commit your changes again.


2 Answers

If you haven't yet pushed your changes, you can also do a soft reset:

git reset --soft HEAD^ 

This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:

git checkout branch git commit -c ORIG_HEAD 

The -c ORIG_HEAD part is useful to not type commit message again.

like image 164
Blair Holloway Avatar answered Oct 04 '22 09:10

Blair Holloway


4 years late on the topic, but this might be helpful to someone.

If you forgot to create a new branch before committing and committed all on master, no matter how many commits you did, the following approach is easier:

git stash                       # skip if all changes are committed git branch my_feature git reset --hard origin/master git checkout my_feature git stash pop                   # skip if all changes were committed 

Now you have your master branch equals to origin/master and all new commits are on my_feature. Note that my_feature is a local branch, not a remote one.

like image 31
fotanus Avatar answered Oct 04 '22 08:10

fotanus