How to undo the last push in Git and revert a Git merge that hasn’t been migrated yet

Let’s assumed you made a push, but now you need to revert this last push due to an error.
How to do it correctly? Master branch

This is usally happens when we works in git environment and need to undo the last push in Git.

There are many commands that can be used to revert a Git merge. I will try to explain you in this post to give you more deep insight.

Solution-1

With the git reflog test, what commit before the merger ( git reflog to be a better option than a git log). Then you can reset it using:

git reset --hard commit_sha
Solution -2

There is another way which you can do.

git reset --hard HEAD~1

Now this will return 1 commit back to you.

Solution -3

Basically, if you worked from the command line and have not yet closed it, you can just see which commit was the last one:

git commit -m "demotest"
[master a703d65] demotest
 1 file changed, 3 insertions(+), 3 deletions(-)

git push
Counting objects: 4, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 407 bytes | 407.00 KiB/s, done.
Total 4 (delta 2), reused 0 (delta 0)
To git.mydomain.tld:folder/repo.git
   543acea..a703d65  master -> master

The last line says that BEFORE the push, the last commit was 543acea, but became a703d65 – so go back to 543acea:

git reset --hard 543acea
git push --force

Also, if you closed the console (or you have a UI in which actions are not visible), but you are sure that you did not do anything after push, the commands will help you:

git reset --hard HEAD~1
git push --force

In general, it is best to read the reflog ( git reflog) and roll back to the desired commit via HEAD @ {1} (specify the number of actions you need to undo in your case):

git reset --hard [email protected]{1}
git push --force

and Open reflog:

$ git reflog

a703d65 (HEAD -> master, origin/master, origin/HEAD) [email protected]{0}: commit: demotest
543acea [email protected]{1}: commit: demotest
1a4e976 [email protected]{2}: commit: something

...

Your task is to find in this log the item to which you want to return:

$ git reset --hard [email protected]{1}

Finally, you are all set with git revert and you can start work again.

About Shachindra Yadav

I, Shachindra Yadav, a Cloud Certified, DevOps and technology enthusiastic person, more passionate to learn and write blogs in my free time.

View all posts by Shachindra Yadav →