© Gennaro Nucaro 2026 | All Rights Reserved
Tutorial: How to cancel a merge in Git.
It often happens to merge into the wrong branch, encounter conflicts during the merge, or simply want to undo the latest changes.
Fortunately, with git, it's simple: just a few commands. Let's see how:
For merges that happened locally, you need to use the command:
--hard means that the index and working directory will be reset, and you will lose uncommitted changes. I recommend not having any changes in progress or creating a backup branch if you are not sure, or doing a git stash. Otherwise, if you have changes in progress, you can use the --merge flag instead of --hard.
<hash-commit-before-merge> should be replaced with the hash of the commit before the merge.
There are different methods to retrieve the hash:
First method
Second method
Tips:
Type q in the console to exit the git viewer after running the commands and return to the console.
Now that you have retrieved the hash, which should be in this format ff29edf, you need to replace it with <hash-commit-before-merge>.
Example:
If the merge was the last operation, you can also use the command:
Useful if the merge was done by mistake.
HEAD~1 in Git refers to the commit immediately before the current commit (HEAD).
If you are working with a remote repository and have committed changes, don't worry! You can still resolve the issue by using the following command:
There are differences compared to git reset: with git revert a new commit will be created that will be present in the history, unlike git reset where we simply delete the commit and there will be no trace in the history. Also, for the hash, we need to use the merge commit hash, unlike git reset where we use the commit hash before the merge.
Use git log --oneline or git reflog to retrieve the hash.
-m 1 tells Git to undo the merge commit considering the first parent as the main one.
© Gennaro Nucaro 2026 | All Rights Reserved