How to cancel a merge in git

Tutorial: How to cancel a merge in Git.

Published:

TL;DR

# For merges that happened locally
git reset --hard <hash-commit-before-merge>
git reset --hard HEAD~1
# For merges committed to the remote repository
git revert -m 1 <hash-merge-commit>
# To retrieve the hash
git log --oneline
git reflog

Introduction

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:

  1. With git reset: for merges that happened locally.
  2. With git revert: for merges that have already been committed to the remote repository.

For merges that happened locally

For merges that happened locally, you need to use the command:

git reset --hard <hash-commit-before-merge>

--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

git log --oneline

Second method

git reflog

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:

git reset --hard 2ad44e7

If the merge was the last operation, you can also use the command:

git reset --hard HEAD~1

Useful if the merge was done by mistake.

HEAD~1 in Git refers to the commit immediately before the current commit (HEAD).

For merges committed to the remote repository

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:

git revert -m 1 <hash-merge-commit>

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.