How to Revert Multiple Commits in Git

Azhar Bashir Khan Feb 02, 2024
  1. Using git revert to Revert Multiple Commits in Git
  2. Using git reset to Revert Multiple Commits in Git
How to Revert Multiple Commits in Git

In this tutorial, we will see about reverting multiple commits in Git.

In Git, we may have done many commits for some feature development or committed a few bug fixes.

We may now decide to chuck this work. Thus, to return the repository to the state before these changes were done, we need to revert the multiple commits done.

We can use the git revert command for reverting multiple commits in Git.

Another way of reverting multiple commits is to use the git reset command.

We will now illustrate both of them with an example.

Using git revert to Revert Multiple Commits in Git

Suppose we have done multiple commits for a few bug fixes.

We can see those commits in the log of Git, as follows.

$ git log --oneline
17b787d bug3 fixed
1fefb57 bug2 fixed
8b3560b bug1 fixed
784065c feature1 developed
...

Now, we decide to chuck away those bug fixes and revert the repository to state before the bug1 fixed state.

Thus, we can use the git revert command with the --no-commit option. The syntax of the command is git revert --no-commit <commit>.

Thus, to revert the three commits of the bug fixes done, we need to do as follows.

$ git revert --no-commit 17b787d784065c
$ git revert --no-commit 1fefb57
$ git revert --no-commit 8b3560b

Thus, the repository in Git is now in the state before committing the bug1 fixed.

We have used the sha1 name of the commits to revert each commit.

We need to commit this state of the working tree in the Git repository as follows.

$ git commit -m "the fixes for bugs 1 2 3 reverted"

Using git reset to Revert Multiple Commits in Git

Suppose we have some merge commits in the repository. Then the above solution using the git revert will not work.

We need to use the git reset command in such cases.

Thus, to revert multiple commits using git reset in Git, we need to do as follows.

$ git reset --hard 784065c
$ git reset --soft ORIG_HEAD
$ git commit

Thus, we have used the git reset command to revert the repository to the commit, 784065c feature1 developed, which was immediately before the first bug fix in the commit history.

Thus this works even when we have some merge commits.

Related Article - Git Commit

Related Article - Git Reset