How to Reset or Revert a File to a Specific Version in Git
There are cases when you need to revert or reset a file to a specific version. With the help of this tutorial you will easily manage it.
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:
Reverting and Resetting a File to a Specific Version
git review the changes made to the file
git diff <sha1-commit-hash> <file-path>To reset a file to the state of a specific commit, run the git restore command (Git 2.23+):
git restore a file to a specific commit
git restore --source=<sha1-commit-hash> <file-path>Alternatively, you can use the git reset command to reset the file in the staging area (index), but note that it does not change the working directory file content:
git reset a file in the index
git reset <sha1-commit-hash> <file-path>You can also effectively use the git checkout command:
git checkout
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
git checkout <sha1-commit-hash>~1 -- <file1-path> <file2-path>Resetting, Reverting and Checking out in Git
<kbd class="highlighted">Git reset</kbd>, git revert and <kbd class="highlighted">git checkout</kbd> 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 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:
- Updating the staging area (index) to match a specific commit. It does not restore file content in the working directory.
- Changing which commit a branch
<kbd class="highlighted">HEAD</kbd>is pointing at. It can adjust the commit history that already exists. - Unstaging a file.
Git Revert
This command helps to:
- Rollback 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.
Git Checkout
This command is used for:
- Moving the
<kbd class="highlighted">HEAD</kbd>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 <kbd class="highlighted">git repository</kbd>, 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.