How to use git to restore a file you deleted ages ago
Say you're working in a git version controlled project and deleted a file or directory ages ago.
You now realise you need the deleted file/directory back.
There are many ways to do this in git. Here's a straightforward one on Linux, using zsh.
Syntax may differ slightly on other systems.
Step 1: Track down in which commit you removed the file(s)
git log --diff-filter=D -- path/to/deleted/stuff
This will show you something like:
commit febc85297a3ad46217d4c5a2068140a23982c6e2 Author: Alice <[email protected]> Date: Tue Mar 20 01:45:16 2018 +0100 Fix the issue in the thing before Bossman finds out.
Step 2: Grab the commit hash and use it to restore the file(s)
git checkout febc85297a3ad46217d4c5a2068140a23982c6e2~1 path/to/deleted/stuff
If all went well, path/to/deleted/stuff is now restored.
Notice the ~1 that I added to the commit hash.
~1 indicates that we're not actually referencing the mentioned commit, but its parent (the commit before the referenced commit).
If you think about it, this makes sense.
The code in the referenced commit doesn't have the deleted file(s) anymore. We need to go 1 commit further back in history to find the files we want to restore.
Not satisfied with my ~1 explanation? See Paul Boxley's article Git caret and tilde.