git revert merge commit — how to undo a merge safely
Quick Answer
# 1. Find the merge commit hash
git log --oneline --graph
# 2. Revert the merge commit
git revert -m 1 <merge-commit-hash>
# 3. Push the new revert commit
git push origin main
When this happens
You already merged a branch and pushed it, but now need to undo that merge without rewriting shared history.
error: commit abc1234 is a merge but no -m option was given.
fatal: revert failed
Merge commits have more than one parent, so git revert needs the -m option to know which parent should be kept as the mainline.
Details
What `-m 1` means
-m 1 tells Git to keep parent 1, which is usually the branch you were on when you ran git merge. The merged-in branch changes are undone.
# Most common case
git revert -m 1 <merge-commit-hash>
Inspect the parents before reverting
git show --summary <merge-commit-hash>
# Or list parents directly
git rev-list --parents -n 1 <merge-commit-hash>
If conflicts happen during the revert
# Resolve conflicts in the files
git status
git add .
git revert --continue
# Or abandon the revert
git revert --abort
Do not use reset on shared branches
If the merge commit is already pushed to a shared branch, prefer git revert over git reset. Reset rewrites history and usually requires a force-push.
# Safer on shared branches
git revert -m 1 <merge-commit-hash>
# Risky on shared branches
git reset --hard <commit-before-merge>
Related