Friday, May 3, 2013

Recovering a deleted file in Linux

As long as there is still a process holding a file open, a deleted file can still be recovered.

Here we simulate the process. In one terminal do:

$ cd /tmp/
$ cat>deleted_file
some thoughts
go here

^D
$ tail -f deleted_file
some thoughts
go here

Since -f blocks this terminal, open another one and do:

$ cd /tmp/
$ lsof deleted_file
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
tail 32664 ant 3r REG 0,29 22 583000 /tmp/deleted_file
$ rm -f deleted_file
$ lsof deleted_file
lsof: status error on deleted_file: No such file or directory
...
$ lsof | grep deleted_file
tail 32664 ant 3r REG 0,29 22 583000 /tmp/deleted_file (deleted)
$ cat /proc/32664/fd/3
some thoughts
go here
$ cp /proc/32664/fd/3 deleted_file
or
$ cat /proc/32664/fd/3 >deleted_file
$ cat deleted_file
some thoughts
go here

You can only reliably recover deleted files that are still open though, e.g. typically database or log files.

No comments: