Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revert a commit and create a new branch from those changes?

Tags:

git

Its late Sunday and I made a bad mistake. I commited and pushed directly into the master branch, where I should have created a branch and pushed the changes to the new branch instead.

So I could do a git revert SHA to revert the last commit with a new commit.

However how about my changes, I don't want to loose them.

Shall I create a branch from already modified Master like git checkout -b feature and then revert the Master branch?

But what happens once I merge back feature into master, will it know that that commit was reverted on Master previously and eliminate it? git merge feature

Btw, there is no history rewriting problem, as I'm the only developer working on this project. Hence I would consider a hard reset, if its the better choice.

Thanks for advice

like image 675
Houman Avatar asked Jul 12 '15 20:07

Houman


People also ask

Does revert create a new commit?

The git revert command is a forward-moving undo operation that offers a safe method of undoing changes. Instead of deleting or orphaning commits in the commit history, a revert will create a new commit that inverses the changes specified. Git revert is a safer alternative to git reset in regards to losing work.


1 Answers

If you are the only developer, then you can do a hard reset. If abc123 is the SHA1 of the accidental commit, then do:

git checkout master
git branch feature-branch
git reset --hard abc123^

This will keep your new commit in the new feature-branch branch (without switching to that new branch yet), and then rewind master back to the previous commit. Then you can push the corrected master branch using git push -f origin master.

like image 123
Greg Hewgill Avatar answered Sep 30 '22 14:09

Greg Hewgill