How to Reset or Revert a File to a Specific Version in Git

If you want to review the changes of the file that were made between the current state and the state of a specific commit, then run the command below:

Watch a course Git & GitHub - The Practical Guide

Reverting and Resetting a File to a Specific Version

If you want to review the changes of the file that were made between the current state and the state of a specific commit, then run the command below:

git diff <sha1-commit-hash> <file-path>

To reset a file to the state of a specific commit, run the git reset command:

git reset <sha1-commit-hash> <file-path>

You can also effectively use the git checkout command:

git checkout <sha1-commit-hash> -- <file1-path> <file2-path>

If you want to reset to the commit before a specific one, append ~1 (where 1 is the number of commits you want to go back , it can be any number):

git checkout  <sha1-commit-hash>~1 -- <file1-path> <file2-path>

Resetting, Reverting and Checking out in Git

Git reset, git revert and git checkout can be related to the most effective tools of Git. The most significant option they offer is undoing changes in the git repository. As the given-above commands are similar, one can easily get confused. Let’s see how to use them without confusion.

Git Reset

The git reset command is used for:

  • Returning the overall working tree to the previous committed state. It will discard commits or clear the changes that were not committed.
  • Changing which commit a branch HEAD is pointing at. It can adjust the commit history that already exists.
  • For unstaging a file.

Git Revert

This command helps to:

  • Rollback the committed changes;
  • Generate a new commit by inverting a specific commit. So, it can add a brand new commit history, yet can’t modify the one that already exists.
  • Overwrite the files that are included in the working directory.

Git Checkout

This command is used for:

  • Moving the HEAD pointer to a particular commit or switching between different branches;
  • Rolling back any changes of content to those of a particular commit;
  • Not making changes to the commit history;
  • Overwriting files in the working directory.

So, whenever you need to undo changes in git repository, you can easily run the above-given commands. Using these commands may seem confusing at first sight, but the more information you have about them, the better you will manage to work.