Appearance
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:
Finding the path of the deleted file
bash
git log --all --full-history -- "*MyFile.*"This command will display all the commits from the commit history that contain changes to files whose names match the given pattern. Hence, we can use the commit hashes found with the help of the command above to get the file path by running the following command:
Showing a list of commits
bash
git show --pretty="" --name-only <sha1-commit-hash>Displaying the specified version of the file
After finding out the file path, we can view the commits where it was changed by running the command below:
Viewing the specified version of the file
bash
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 that we want to restore by running the command below:
Finding the specified version of the file
bash
git show <sha1-commit-hash> -- <path-to-file>Restoring the file to the working copy
To restore it to your working copy, use the git checkout command:
Restoring the file with git checkout
bash
git checkout <sha1-commit-hash>^ -- <path-to-file>The caret symbol (^) gets the version of the file from the previous commit. At the time of the <sha1-commit-hash> commit, the file may have been deleted, so you need to look at the previous commit to get the contents of the deleted file(s).
Note: In modern Git versions (2.23+),
git checkoutis deprecated for file restoration. Usegit restoreinstead:bashgit restore --source=<code>{{ '\u003csha1-commit-hash\u003e' }}</code>^ -- <code>{{ '\u003cpath-to-file\u003e' }}</code>
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 --all option 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.