Houman
Houman

Reputation: 66320

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

It's late Sunday and I made a bad mistake. I committed 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 it's the better choice.

Upvotes: 16

Views: 14332

Answers (2)

Coder Gautam YT
Coder Gautam YT

Reputation: 2147

A generalized version of the above answer, revert back to any commit in time while keeping latest code in new branch

I had this issue many times.

First, use the git log command to find the commit SHA you want to revert to.

Once you got that, follow these commands in order (use main instead of master depending on your repo):

1. git checkout master
2. git branch dev-changes
3. git reset --hard commit_hash_before_your_changes

4. git push origin master --force

5. git checkout dev-changes
6. git push origin dev-changes

This way you can revert your master branch back to a commit you want, while keeping your commits afterward on a new branch.

Hope it helps!

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 992737

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.

Upvotes: 13

Related Questions