How to Undo Merge in Git: Simple Commands Explained
To undo a merge in Git, use
git merge --abort if the merge is in progress and not committed yet. If the merge is already committed, use git reset --hard HEAD~1 to revert to the state before the merge.Syntax
git merge --abort: Stops the merge process and returns to the state before the merge started if the merge is not committed yet.
git reset --hard HEAD~1: Moves the current branch pointer back by one commit, discarding the merge commit and all changes made by it.
bash
git merge --abort
git reset --hard HEAD~1Example
This example shows how to undo a merge that has been committed by mistake.
bash
git checkout main # Merge feature branch into main git merge feature-branch # Realize the merge was a mistake # Undo the merge commit # Option 1: If merge is in progress and not committed # git merge --abort # Option 2: If merge is committed git reset --hard HEAD~1
Output
HEAD is now at <commit-hash> Commit message before merge
Common Pitfalls
- Trying
git merge --abortafter the merge commit is made will fail because the merge is already finished. - Using
git reset --hardwill discard uncommitted changes, so make sure to save work before running it. - Undoing merges on shared branches can cause conflicts for others; communicate before rewriting history.
bash
git merge --abort # Works only if merge is not committed git reset --hard HEAD~1 # Use carefully, discards changes
Quick Reference
| Command | When to Use | Effect |
|---|---|---|
| git merge --abort | During a merge conflict before commit | Cancels the merge and restores previous state |
| git reset --hard HEAD~1 | After merge commit to undo merge | Removes the merge commit and resets files |
| git reflog | To find previous commits | Shows history of HEAD movements for recovery |
Key Takeaways
Use
git merge --abort to cancel an ongoing merge before committing.Use
git reset --hard HEAD~1 to undo a merge commit and reset the branch.Always save uncommitted work before using
git reset --hard to avoid data loss.Communicate with your team before undoing merges on shared branches to prevent conflicts.
Use
git reflog to recover lost commits if needed.