Rollback a Git merge
How can you roll back a Git merge safely? Learn what steps to take when a merge goes wrong or isn't needed, using Git commands to undo the changes and restore your previous state.
Rolling back a Git merge can be necessary when something goes wrong or if you merged the wrong branch by mistake. Don’t worry—Git gives you a few ways to undo the merge depending on whether it was committed or not.
If the merge is not yet committed:
You can easily cancel the merge using:
git merge --abort
- This restores your working directory to the state before the merge.
- Only works if there are no staged changes.
Alternatively, you can use:
git reset --hard HEAD
This discards all changes and resets the branch to the last commit.
Warning: Any unsaved work will be lost!
If the merge was already committed:
You’ll need to undo the merge commit using git reset or git revert.
To remove the merge commit and all changes:
git reset --hard HEAD~1
- This will roll back the entire merge as if it never happened.
- Use with caution—especially on shared branches.
To revert the merge commit safely (preserves history):
git revert -m 1
- -m 1 tells Git which parent to keep.
- Ideal for undoing merges on shared/public branches.
Quick Tips:
- Always make sure to commit or stash your current changes before resetting.
- Use git log to identify the merge commit hash if needed.
- For safety, create a backup branch before rolling anything back.