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:

git

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:

git revert -m 1

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:

  1. Git will pause and mark conflicting files.

  2. Resolve conflicts manually by editing the files.

  3. Add the resolved files:

    git
  4. Continue the revert:

    git revert --continue

To abort the revert if needed:

git revert --abort

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:

git

Example Workflow

Initial State:

You have a merge commit on the main branch:


Revert the Merge Commit:

git revert -m 1

This creates a new commit that undoes the changes introduced by feature-branch.

Key Considerations

  1. 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.

  2. Avoid Reverting Active Branches: If you revert a merge commit and the feature branch is still active, it may reintroduce conflicts when merged again.

  3. 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.

A single code search interface for all your repos

Search across all your repos (GitHub, GitLab, BitBucket, etc) using a single open-source, blazingly fast, and feature-rich interface.

A single code search interface for all your repos

Search across all your repos (GitHub, GitLab, BitBucket, etc) using a single open-source, blazingly fast, and feature-rich interface.