revert or reset file in git

How to Reset or Revert File to Specific Commit in Git

Git is a popular version control system used by many developers & software teams. It provides tons of great features with easy to use commands. While working with Git, we regularly work with files and commit changes to them. Sometimes you may need to reset or revert file to specific commit in Git. In this article, we will learn how to reset or revert file to specific commit in Git.


How to Reset or Revert File to Specific Commit in Git

Here are the steps to reset or revert file to specific commit.

1. Find Commit for File

If you don’t know which commit you want to revert or reset your file to then run the following command to list all commits made to the file. Replace <file_path> with the path to file.

$ git log --follow -- <file_path>

The above command will list all commits along with their commit messages, author, date and commit ID. You can use this information to find out the specific commit that you want to revert or reset your file to.

2. Revert File to Commit

Once you have determined the commit to which you want to restore your file you can revert it using the following command. Replace <commit_id> with the commit ID to which you want to revert the file. Replace <file_path1>, <file_path2> with the paths of files that you want to revert. We have mentioned 2 file paths but you can use just one if you want to revert only one file.

$ git checkout <commit_id> -- <file_path1> <file_path2> 

If you want to revert to commit that is 5 commits before the above commit, you can add ~5 after the commit id in above command.

$ git checkout <commit_id>~5 -- <file_path>

Alternatively, you can also use git reset command to revert the file.

$ git reset <commit_id> <file_path>

If you want to check the different between the file’s latest version and the version in old commit, you can run git diff command for this purpose.

$ git diff <commit_id> <file_path>

In this article, we have learnt how to revert file to specific commit. This is a very common problem faced by many developers new to git. The key is to find the right commit hash ID to which you want to revert your file.

Also read:

How to Find & Restore Deleted File in Git
How to Set Vim Default Editor in Git
How to Use Variable As Key in JS Object
How to Format Number as Currency String
How to Access iFrame Content With JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *