How to Find a Deleted File in the Project Commit History in Git
There are situations when you have deleted a file in the project, and now you want to get it back. Here, we suggest a solution to this issue. Follow the steps below and solve the problem.
Steps to finding and restoring a deleted file¶
Finding the file path¶
If you have deleted a file and do not know on which path it was, then you should execute the following command:
git log --all --full-history -- "*MyFile.*"
This command will display all the commits from the commit history that contain changes on the files, whose names match the given pattern. Hence, we can use the commit hashes found with the help the command above to get the file path by running the following command:
git show --pretty="" --name-only <sha1-commit-hash>
Displaying the specified version of the file¶
After finding out the file path, we can bring out the commits on which it was changed by running the command below:
git log --all --full-history -- <path-to-file>
Now we have the file path and the commits where it was changed, so we can find the version of the file, which we want to restore by running the command below:
git show <sha1-commit-hash> -- <path-to-file>
Restoring file into working copy¶
For restoring it into your working copy using the git checkout command:
git checkout <sha1-commit-hash>^ -- <path-to-file>
The caret symbol (^) gets the version of the file of the previous commit. At the moment of <sha1-commit-hash> commit, the file can be deleted, so you need to look at the previous commit to get the contents of the deleted file(s).
The git log Command¶
The git log command shows committed snapshots used for listing and filtering the project history and searching for particular changes. It is a tool used for examining a repository’s history and finding a particular version of a project. The --alloption shows all the commits in the history of branches, tags, and other references. The --full-history option simplifies the history explaining the final state of the tree.
The git checkout Command¶
The git checkout command is used for switching branches or restoring working tree files. It operates on files, commits, and branches. It allows switching between multiple features in just a single repository. The git checkout command works with the git branch command. It updates the files in the working directory to match the version stored in that branch, instructing Git to record all the new commits.