Restoring a file

If we deleted a file and we want to restore it to the previous state we run

git restore --source=HEAD~1 file_path/file_name.ext

Here we are restoring a deleted file to the version that was available in the commit previous to deleting it. But we can use this strategy to for file from any point in the history of our repository.

Restoring a file 1
Restoring a file 2

As an example, take a look at the image on the left. file2.txt has only one line in it, sky. Then we add hello and commit the changes, and finally we add world and commit the changes.


file2.txt has not been deleted. It still exists in our working directory. So, say we want to revert file2.txt to a previous state when it only had the word sky in it. To do this we run

git restore --source=HEAD~2 file2.txt

With this, Git will restore it to two steps behind the HEAD pointer of our repository, when the file only said sky. If we want to keep the changes as they were at this point in time, we can commit file2.txt to our repository.