Finding And Restoring A Deleted File In Git

### TL;DR

If you delete a file and need to restore it but don't know the path you can search for it with the argument to the last `grep` in this command:

Once you find the filepath you're after, look for the commits that affected it with:

Find the commit where you deleted the file and pull it back by using `~1` after the commit ID.

At that point, it'll be staged in your existing branch and ready to commit.

I did a Digital Garden redesign of my site a few weeks ago. I switched over to Tailwind for CSS during the process. When I made the jump, I remove my old CSS files. Today, I realized that my custom code syntax highlighting was part of the purge. Here's how I got it back.

My site is stored in a git repository. I wasn't sure what the file was named, but I new it was a SCSS file and had that extension. So, I ran this command to get the file name:


- `git log` outputs the logs of the repo - `--diff-filter=D` limits the logs to just the deletes - `--summary` changes the output format so that includes the actions on the specific files that were modified.

For example, `git log` without `--summary` produces this:

- `--reverse` flips the order of the output so that the most recently deleted files are at the end of the run (which makes them easier to find). - `grep delete` pull out just the lines with the file paths in them. So, instead of:

We get simply:

- And finally, `grep scss` is what I used to find the SCSS files.

Scrolling back through the output, I found the file I was after:

Now I've got the filename and can search for the commits the included it with via:

This returns:

So, the commit where I deleted the file was `13e190c2a04b0cb96d7e8573e9187f6aae30625f`. I need to checkout the file from the commit _before_ that one. This is done by adding `~1`. This is the command I ran:

If you get something like this error it means you didn't add the `~1`:

Once you do the checkout it'll restore the file and stage it so it's ready to be committed back into your repo and you're all set.