How to Revert a File to a Previous Commit in Git

Azhar Bashir Khan Feb 02, 2024
How to Revert a File to a Previous Commit in Git

Git is a version control system. We use it to keep track of the changes done to files in our project directory. In a collaborative development environment, many team members often work on the same files and change those.

We often face a situation where we no longer find the current version of the changes to a file suitable for our purpose. Thus, we would like to revert such a file to a specific, previous version of that file in such cases.

Using Git, we can accomplish reverting the file to a previous commit.

This tutorial will teach how to revert a file to a previous commit in Git. We will illustrate this with an example.

Revert File to a Previous Commit in Git

We use Git in a collaborative development environment to keep track of the changes done to files. Git accomplishes this task of tracking the changes to the files using commits.

Thus, using the commit history of the files, we view the various changes done to the files across the different versions.

Often, we might encounter a situation where we find that the file’s current version is no longer suitable for our needs. Also, we find that a particular revision in the file’s commit history is more attuned to our current need.

Thus, in such a case, we would like to revert the file to that previous version or commit in the commit history in the Git repository.

Suppose we have a file named README.md in our project Git repository. We can browse the commit history of that file with the git log command as follows.

$ git log --oneline README.md
814b51e Updated README.md, further notes
9cbe84d Updated README.md, added some notes
dfe8d6c Initial commit

We find that the version of the file README.md at the commit given by SHA hash 9cbe84d is what we desire.

We can use the command git checkout for this. The command’s syntax to revert a file to the previous commit is git checkout <commit> -- <file-to-revert>.

Thus, we need to do the following to revert the file README.md to the version given by the commit given by SHA hash 9cbe84d.

$ git checkout 9cbe84d -- README.md

The README.md file is reverted to the previous commit given by SHA hash 9cbe84d.

Please note to use the git checkout command with caution. The local changes done to the file are discarded. Git replaces the file with the given committed version.

Be sure to use this only if you are sure and don’t want those unsaved local changes.

Thus, we have shown how to revert a file to a previous commit in Git.

For more information, please visit the following links.

  1. git-checkout
  2. Git Basics - Undoing Things