Table of Contents
Introduction
When working with Git, you will likely need to merge branches at some point. However, sometimes a merge may introduce bugs or other issues that you want to undo. Fortunately, Git provides several methods for reverting a merge:
Key methods covered in this guide:
- Using
git reset
to undo a local merge - Using
git revert
to reverse a merge commit - Handling remote merge reverts after push
Prerequisites
Before undoing a merge, you should:
- Have a clean working directory with no uncommitted changes
- Identify the merge commit or parent commit you want to return to
- Confirm the merge commit has not already been pushed to the remote repository
Using git reset
to Undo a Local Merge
To undo a merge that has not yet been pushed remotely:
- Checkout the branch where the merge commit was made
- Use
git reflog
to find the commit ID of the merge - Run
git reset --hard <commit>
using the parent commit’s ID
For example:
git checkout master
git reflog
# find merge commit id
git reset --hard abc1234
This will move the master
branch pointer back to before the merge.
Key notes on using git reset
:
- Resets the branch to the specified commit
- Discards any changes from later commits
- Works for local commits only
Using git revert
to Reverse a Merge
The git revert
command:
- Creates a new “revert commit” that reverses the changes
- Keeps commit history and doesn’t discard commits
- Can be used after push (with some caveats)
To use it:
git revert -m 1 <merge_commit_hash>
git push
The -m 1
flag specifies the parent commit to revert to.
Key notes on using git revert
:
- Safer alternative to
git reset
in most cases - Preserves existing commits
- Can handle remote merges in some cases
Handling Remote Merge Reverts
If a merge has already been pushed remotely, resetting or reverting gets more complex:
- Resetting can cause issues for other developers
- Pushed reverts require force pushing the branch
In this case it’s best to:
- Revert the merge locally
- Force push the branch to overwrite history (
git push -f
) - Ask teammates to reset their remote branch to match (
git reset --hard origin/<branch>
)
While more disruptive, this will undo the remote merge.
Conclusion
- Use
git reset
to undo a local unpushed merge - Leverage
git revert
to reverse merge commits - Handle remote merges carefully to avoid issues
Following these best practices will let you safely undo Git merges when needed.