How to Revert a Merge in Git
Reverting a merge commit in Git can be tricky because it involves changes from two parent branches. The git revert
command allows you to undo the changes introduced by a merge commit without modifying the commit history. Here's how to do it.
1. Identify the Merge Commit
First, locate the hash of the merge commit you want to revert. Use:
Merge commits will typically have messages like "Merge branch 'feature-branch' into 'main'." Note the hash of the merge commit (e.g., abc123
).
2. Revert the Merge Commit
Run the following command:
Here:
-m 1
specifies which parent branch to keep.<merge-commit-hash>
is the hash of the merge commit.
Understanding -m 1
Merge commits have two parent commits:
Parent 1: The branch you merged into (e.g.,
main
).Parent 2: The branch you merged from (e.g.,
feature-branch
).
Using -m 1
means you are keeping the changes from Parent 1 while undoing the changes from Parent 2.
3. Resolve Any Conflicts
If conflicts arise during the revert:
Git will pause and mark conflicting files.
Resolve conflicts manually by editing the files.
Add the resolved files:
Continue the revert:
To abort the revert if needed:
4. Commit the Revert
Once the revert is complete, Git will automatically create a new commit that undoes the changes introduced by the merge commit. Push this new commit to the remote repository if necessary:
Example Workflow
Initial State:
You have a merge commit on the main
branch:
Revert the Merge Commit:
This creates a new commit that undoes the changes introduced by feature-branch
.
Key Considerations
Reverting vs. Resetting:
Reverting creates a new commit to undo changes and preserves history.
Resetting removes commits entirely and rewrites history, which can disrupt shared repositories.
Avoid Reverting Active Branches: If you revert a merge commit and the feature branch is still active, it may reintroduce conflicts when merged again.
Collaborative Workflows: Communicate with your team before reverting a merge commit to avoid confusion.
Summary
Use
git revert -m 1 <merge-commit-hash>
to undo a merge commit.Resolve conflicts if necessary, then continue the revert.
Commit and push the changes to finalize the process.
Reverting a merge commit is a safe and effective way to undo changes while maintaining a clear and traceable commit history.