Data report"State of code review 2024" is now liveRead the full report

How to revert a merge in Git

Kenny DuMez
Kenny DuMez
Graphite software engineer


Note

This guide explains this concept in vanilla Git. For Graphite documentation, see our CLI docs.


Reverting a merge in Git can be necessary when a merge introduces errors into the main branch or disrupts the project's stability. This guide will explore the methods to safely revert a merge commit in Git, using commands and strategies to ensure your repository remains clean and functional.

Before diving into the commands, it's important to understand when and why you might need to revert a merge. A merge commit typically occurs when you integrate changes from one Git branch into another, typically from a feature or development branch into the main branch. If this merge introduces errors, performance regressions, or other issues, reverting it can quickly restore the project to a stable state.

First, ensure you have the latest version of your repository by pulling the latest changes from your remote repository:

Terminal
git pull origin main

Next, identify the merge commit you want to revert. You can use git log to view the commit history. Look for entries labeled as "Merge" along with the summary of changes:

Terminal
git log --oneline --graph

To revert a merge commit, you’ll use the git revert command followed by the hash of the merge commit. However, reverting a merge commit differs slightly from reverting a normal commit. You must specify which parent commit of the merge you want to revert to, typically the main branch’s state before the merge.

Here's how to revert to the first parent of the merge commit, which usually represents the state of your branch before the merge:

Terminal
git revert -m 1 <merge_commit_hash>

Here, -m 1 tells Git to keep the changes of the first parent (the branch into which changes were merged), effectively undoing the merge.

Imagine you've merged a feature branch called feature/login-update into main, but then realized the feature contained a bug. To revert the change:

  1. Find the merge commit hash:

    Terminal
    git log --oneline --graph
  2. Revert the merge commit:

    Terminal
    git revert -m 1 <commit_hash>

    Replace <commit_hash> with the actual commit hash.

  3. Resolve any conflicts that arise. Git will prompt you to resolve conflicts manually if the revert affects areas of the codebase that have been changed since the merge.

  4. Commit the revert:

    Terminal
    git commit -m "Revert feature/login-update merge"
  5. Push the changes to the remote repository:

    Terminal
    git push origin main

For further reading on reverting merges in Git, see the official Git documentation.

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2