14

I have a file that was deleted, but is still held open by a program. I found the inode number using lsof. How can I create a hard link back to that inode?

Jeff Ferland
  • 20,987

3 Answers3

31

You can't create a link to it, but you can get it back. Let's do an experiment:

$ echo blurfl >myfile.txt
$ tail -f myfile.txt &
$ rm myfile.txt

myfile.txt is now gone, but the inode is kept alive by the tail command. To get your file back, first find the PID of the process keeping the inode:

$ ps auxw | grep tail
sunny      409  0.0  0.0   8532   824 pts/5    S    18:07   0:00 tail -f myfile.txt

The PID is 409. chdir to /proc/409/fd/ and list the contents:

dr-x------ 2 sunny sunny  0 2009-07-24 18:07:18 .
dr-xr-xr-x 7 sunny sunny  0 2009-07-24 18:07:17 ..
lrwx------ 1 sunny sunny 64 2009-07-24 18:07:33 0 -> /dev/pts/5
lrwx------ 1 sunny sunny 64 2009-07-24 18:07:33 1 -> /dev/pts/5
lrwx------ 1 sunny sunny 64 2009-07-24 18:07:18 2 -> /dev/pts/5
lr-x------ 1 sunny sunny 64 2009-07-24 18:07:33 3 -> /home/sunny/tmp/myfile.txt (deleted)

The /proc/[PID]/fd/ directories contain symlinks to file descriptors of all files the process uses. In this case the symlink "3" points to the deleted file. So, to restore the file, copy the contents to a new file:

$ cat 3 >/home/mydir/saved_file.txt
sunny256
  • 861
2

to get the whole file if it is still written to try tail -c +1 -f

from: https://unix.stackexchange.com/questions/25527/how-to-follow-a-la-tail-f-a-binary-file-from-the-beginning

(btw: ln from the fd on /proc doesn't work, just tried that)

eMBee
  • 21
-8

There is no portable way to do this under Linux. Best way would probably be to get all activity on the file-system to cease, kill the program that holds the file open, unmount the file system and use a file-system debugger to re-attach it to a directory. If you have the file system exported through NFS, at least some versions of NFS may allow you to read the file data across NFS.

Vatine
  • 5,560