Merges are essential in Git, but sometimes they go wrong. Reverting a merge commit is different from reverting a regular commit, so it requires special attention.
⚠️ Understand the Context
A merge commit combines histories of two branches and usually has two parents. Reverting it blindly can lead to conflicts or unexpected behavior.
🛠️ Reverting a Merge Commit
Step 1: Identify the Merge Commit
Use git log
to find the commit hash:
git log --oneline
Look for the merge commit you want to revert. It will typically say something like:
abcd123 (HEAD -> main) Merge branch 'feature-branch'
Copy the hash (e.g., abcd123
).
Step 2: Revert the Merge Commit
To revert a merge commit, you must tell Git which parent to revert to using the -m
flag:
git revert -m 1 abcd123
-m 1
tells Git to use the first parent (usually the main branch) and ignore the merged-in changes.- If you want to keep the changes from the branch you merged in and discard the base branch’s, you’d use
-m 2
.
Step 3: Resolve Conflicts (If Any)
Git may prompt you to resolve merge conflicts during the revert. If so:
- Open the conflicting files
- Fix the issues
- Stage the resolved files:
git add .
- Then complete the revert with:
git commit
✅ Example Scenario
You merged feature-branch
into main
, but now want to undo that merge:
git revert -m 1 <merge_commit_hash>
This creates a new commit that undoes the changes introduced by the merge, without deleting any history.
❌ What Not to Do
- Don’t use
git reset
if you’ve already pushed the merge commit to a shared repo. - Avoid deleting history on shared branches—use
revert
to preserve commit history cleanly.
Summary Table
Command | Purpose |
---|---|
git log --oneline | Find merge commit hash |
git revert -m 1 <merge-hash> | Revert merge using first parent |
git revert -m 2 <merge-hash> | Revert merge using second parent |
git add . && git commit | Resolve and finalize the revert |
💡 Pro Tip
If you’re unsure which parent is which, you can run:
git show <merge-hash>
This shows you the parents and changes made by the merge, helping you decide the correct -m
value.