Undoing operations in Git is often an underrated feature. Merging code that wasn’t meant to be merged (yet) is something that could happen to all of us. To be honest, we’ve all been there. Here’s another Git nugget on how to revert merge commits.
Prerequisites
- Git
Solution
You might have one of following two scenarios.
Undo a local merge
Use git reset --hard HEAD~1
to go back to the previous commit before merging. Or, if that was a long time ago:
Step 1. Find the commit before merging by running git reflog
. Step 2. Execute: git reset --hard <commit-SHA1>
.
Undo a pushed to remote merge
git revert -m 1 <merge-commit-SHA1>
git revert
: Creates a new commit. Git: restore vs reset vs revert vs rebase-m 1
: Specifies the parent number (branch) we want to keep and merging into considering there can be Git merge commits with more than one parent.<merge-commit-SHA1>
: The merge commit hash.
Conclusion
To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.