[How to find and restore a deleted file from the project git commit history]
Once upon a time, there was a file in my project that I would now like to be able to get.
The problem is: I have no idea of when have I deleted it and on which path was it at.
How can I locate the commits of this file when it existed?
Suppose you want to recover a file called MyFile, but are uncertain of its path (or its extension, for that matter):
Prelim.: Avoid confusion by stepping to the git root
A nontrivial project may have multiple directories with similar or identical names.
> cd <project-root>
Find the full path
git log --diff-filter=D --summary | grep delete | grep MyFile
delete mode 100644 full/path/to/MyFile.js
full/path/to/MyFile.js
is the path & file you're seeking.
Determine all the commits that affected that file
git log --oneline --follow -- full/path/to/MyFile.js
bd8374c Some helpful commit message
ba8d20e Another prior commit message affecting that file
cfea812 The first message for a commit in which that file appeared.
Checkout the file
If you choose the first-listed commit (the last chronologically, here bd8374c), the file will not be found, since it was deleted in that commit.
git checkout bd8374c -- full/path/to/MyFile.js
error: pathspec 'full/path/to/MyFile.js' did not match any file(s) known to git.
Just select the preceding (append a caret) commit:
git checkout bd8374c^ -- full/path/to/MyFile.js
Note, this was one of several answers on StackOverflow -- I liked it best but there were several others worth reading.