How to Revert a Git Merge Commit

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:

  1. Open the conflicting files
  2. Fix the issues
  3. Stage the resolved files: git add .
  4. 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

CommandPurpose
git log --onelineFind 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 commitResolve 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.

Sharing Is Caring:

Leave a Comment