Recover Deleted Linux Files With lsof

To try this out, create a test text file, save it and then type less deleted.txt. Open another terminal window, and type rm -f deleted.txt. If you try ls deleted.txt you’ll get an error message.

But less still has a reference to the file.:

> lsof | grep testing.txt
less	4607	nithins 4r  REG 254,4   21
           8880214 /home/nithins/deleted.txt (deleted)

Take the PID of  the process, second column  that has the file open (4607), and the fourth one, which gives you the file descriptor (4). Now, look in /proc, and there you will see  a reference to this inode, from which we can copy the file back:

> ls -l /proc/4607/fd/4
lr-x------ 1 nithins nithins 32 Apr  18 02:59
             /proc/4607/fd/4 -> /home/nithins/deleted.txt (deleted)
> cp /proc/4607/fd/4 deleted.txt.bak

Note: don’t use the -a flag with cp, as this will copy the (broken) symbolic link, rather than the actual file contents.

In the same way you can recover apache files (config/log) from the parent process PID if it was deleted accidently.  Try out..!