Linux: How to recover deleted Files?

Posted by Jonas Frederic Schmidt on July 11, 2021 · 1 min read

First Phase: Anger

It has probably happened to every developer at least once: You are working on a difficult problem, finally finding after hours a solution and finishing work happily. But later or the next day you want to look at your code again and are shocked to find out that the file with your code has disappeared. You search for the file but can’t find it. You must have deleted it by mistake. But what do you do now?

In this blog post I will show you how you can restore your deleted source code in many cases and save hours of development work.

Second Phase: There is Hope

Think about what unique string exists in your code. Then search in the hard-drive with:

grep -a -C 200 'unique pattern' /dev/vda1 | tee /tmp/recover

Here vda1 is the partition containing the lost file. You can check this with mount if you are unsure. The grep command will take 200 lines before and after each matching line which is why some irrelevant data will also be included. Open the recover file with a text editor and search for your unique pattern.

Third Phase: Lesson learned

From now on you should really commit your code and also push it into a remote repository immediately after you have completed an important work step. But we all know that some things have to be learned the hard way.