To undo a Git merge that hasn’t been pushed yet, use git reset
to revert your branch to the state before the merge. Here’s how to do it safely:
Step-by-Step Solution
- Check the current state (optional):
git status # Ensure you're in a clean state
- Reset to the pre-merge commit:
- Use
ORIG_HEAD
(Git’s reference to the commit before the merge):bash
git reset --hard ORIG_HEAD
- OR use the specific commit hash (found via
git reflog
):bash
git reset --hard <commit-hash-before-merge>
Key Notes
- Works for un-pushed merges: This method is safe if you haven’t pushed the merge to a remote repository.
- Loses uncommitted changes: Use
git stash
first if you have unsaved work. - For conflicted merges: If the merge was interrupted (e.g., due to conflicts), use:
git merge --abort # Aborts the merge process entirely
Example Workflow
# Start a merge (e.g., git merge feature-branch)
# Realize the merge is incorrect
# Undo the merge:
git reset --hard ORIG_HEAD
# Verify the log:
git log --oneline # The merge commit is gone
What If the Merge Was Fast-Forwarded?
If the merge was a fast-forward (no merge commit created), use:
git reset --hard HEAD@{1} # Revert to the previous state
Clean Up Untracked Files (Optional)
After undoing the merge, remove any leftover files:
git clean -fd # Deletes untracked files/directories (use with caution!)
Summary
Scenario | Command |
---|---|
Undo a completed merge | git reset --hard ORIG_HEAD |
Abort a conflicted merge | git merge --abort |
Undo fast-forward merge | git reset --hard HEAD@{1} |
Once reset, you can re-attempt the merge or push your branch safely.