Sometimes you want to recover a file you deleted from a git repository.
Sometimes you want to recover a file somebody else deleted from a git repository.
Recovering a deleted file from the git repository, after a commit, is not complicated if you know the right commands and method for doing so. This quick tutorial walks you this the recovery processes. The process takes 3 steps:
- Find all of the files deleted from the repository
- Find information about the specific file we are interested in
- Restore the file!
That is all there is to it. Let’s get started.
List all files that have been deleted from a git repository:
git log --diff-filter=D --summary | grep delete
If you know the exact filename of the deleted file you can skip this step.
List information about a particular filename that has been deleted from a git repository:
git log -- [deleted-filename]
Restore a file that has been deleted from a git repository:
Next you are ready to find the last commit before the file was deleted:
git rev-list -n 1 HEAD -- [deleted-filename]
Now that you have the last commit, check out the repository at the commit BEFORE the file was deleted:
git checkout ~1 -- [deleted-filename]
That is it. Your deleted file has been recovered.