How To Recover a Deleted File that was Committed to Git and/or GitHub

So you deleted a file you shouldn't have and now you need to undo your mistake. We've all been there and lucky for us, with git it's fairly straightforward.

Step 1: Find the last commit that modified the file

We first need to find the file that modified our file last. To do that we run the command below:

git rev-list -n 1 HEAD -- <file_path>

This outputs the hash of the commit that deleted the file.

Step 2: Restore the deleted file

To restore the deleted file, we need to checkout the version at the commit before the one that deleted the file. We do this by running the following command:

git checkout <deleting_commit>^ -- <file_path>

The caret (^) symbol tells git to fetch the commit before the one we obtained in step 1

Step 3: Celebrate

With that, you should have your previously deleted file seated in your staged files ready to be committed back into git.