How to Revert a Git Repository to a Previous Commit

The Git Revert Command

One of the most frequently raised questions while dealing with Git is “How to revert a git repository to a previous commit?”. Such action can be possible with the git revert.

Git revert belongs to the “undo” category operations, yet it’s not a classic undo command. The git revert command is applied to undo changes to the commit history of the repository. The git revert command allows you to pick a single commit, converse the changes and, finally, generate a completely new one. In this tutorial, we are going to show you how to revert to the previous state by using Git commands.

The git revert command looks like this:

git revert HEAD

If you have added a new file, named “contact us.htm” and after which you realize that you don’t need the file, named “about-us.htm” any longer, you can simply revert to the stage when you made that commit. The command is the following:

git revert 1a890e7

After this step Git will show you the following note:

Revert "Added about-us.htm"

This reverts commit 1a890e7980283e348cde0444cabe709f6342a851.

To complete reverting, you can choose between saving the given note or creating your own. The result will look like this:

[master 2bbaed3] Revert "Added about-us.htm"

1 file changed, 1 deletion(-)

delete mode 100644 about-us.htm

In case you decide to revert an already published commit, you should start from checking out the repository, then apply git revert and finish the action by publishing it. The command will look like this:

git revert 1a890e7980283e348cde0444cabe709f6342a851
git push origin

Generally, we can distinguish 2 significant advantages of git revert. They are as follows:

  1. The revert command can be effectively applied to a specific commit.
  2. It doesn’t change the history of the project. This means that it’s a completely secure operation for commits, which were already sent to the shared repository.

Git revert and git reset

The most significant difference between git revert and git reset is that the git revert command targets a specific commit not removing all the coming commits. On the contrary, using the git reset command will remove the overall coming commits. Let’s say you are going to undo a commit with the usage of the git reset command, you need to remove the whole commits coming after the targeted one. Generally, git revert is the most secure alternative of git reset. Although the process may seem quite complicated, it becomes pretty easy after going through it several times.


Do you find this helpful?

Related articles