Recovering Deleted Data

Here’s what I did.


cp file ..

Well, I already had a file called file in the parent directory. Whoops!

Here’s what I did to fix it.

grep -a -b "text in the deleted file" /dev/sda3
530159385076:some text in the deleted file

dd if=/dev/sda3 count=8 skip=$(expr 530159385076 / 512 - 4)

/dev/sda3 is my /home partition, so I’m grepping the hard drive directly. That’s what the -a flag is for — it looks at binary as if it’s text. The -b flag prints the byte offset, so we know where on the drive it found the match.

Then we use dd to grab the data. count=n takes n blocks (512 bytes by default, can be changed with bs=n) and skip=n skips n blocks in. Here I go back 4 blocks and take 8, which was enough in my case. When/if it works, add of=file to get the file back. It might need editing to remove some binary.

An alternative is to give grep the -C200 flag. This gives 200 lines before and after the string for context. Maybe you can avoid dd then.

This should work in most cases, unless the filesystem has already allocated the space to another file. It obviously won’t work on encrypted discs, or if you used something like shred. It has worked for me one out of two times (the other time it borked my terminal), so YMMV.

It can take a really long time.