DEV Community

Gabrielle Jacobs
Gabrielle Jacobs

Posted on • Originally published at gabbysadventure.com on

2 1

Git Revert: aka How to delete a commit without losing other commits

I was pair programming and my partner somehow merged another pair’s branch and made several commits after. My partner never did a git merge so we were confused how that happened. But the important thing is… HOW DO WE FIX IT?!

I worried it would be very difficult and risky like doing a git rebase or something, but luckily it’s a very simple fix.

Revert a normal commit

git revert <commit hash>
Enter fullscreen mode Exit fullscreen mode

Revert a merge commit

git revert <commit hash> -m 1
Enter fullscreen mode Exit fullscreen mode

Note that commit hash is the 7 character id associated with the commit you want to delete.

You will then be asked to add your commit message as you would a normal commit. Then git push.

That’s it! You’re done!


Extra explanation for those who want it…

What is -m 1? The -m specifies the parent number and merge commits have more than one parent. Git doesn’t know automatically which parent branch is the main one and which one you want to un-merge.

When you do a git log, you will see next to Merge, the parent branches

commit 8f937c683929b08379097828c8a04350b9b8e183
Merge: 8989ee0 7c6b236
Author: John Doe <john@example.com>
Date: Wed Oct 21 22:49:41 2020 +0100
Enter fullscreen mode Exit fullscreen mode

In this situation, git revert 8f937c6 -m 1 will get you the tree as it was in 8989ee0, and git revert -m 2 will reinstate the tree as it was in 7c6b236.

If you merged another branch with your’s, then your branch is most likely the first one so -m 1 will be what you use.

Hopefully this has helped someone to become 1 step closer to becoming a better developer.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay