Skip to content

Instantly share code, notes, and snippets.

@jeviolle
Last active June 3, 2017 04:34
Show Gist options
  • Save jeviolle/9698949 to your computer and use it in GitHub Desktop.
Save jeviolle/9698949 to your computer and use it in GitHub Desktop.
Recover a deleted open file in linux
This is simple to test.
Step 1
Create a test file
$ echo "OMG Please dont delete me" > /tmp/myfile.text
Step 2
Do something to hold on to the open file (do not close the process obviously)
$ irb
irb(main):001:0> File.open('/tmp/myfile.text')
=> #<File:/tmp/myfile.text>
See the file being open with 'lsof'
$ lsof | grep myfile
irb 21505 veewee 3r REG 253,0 26 417220 /tmp/myfile.text
Step 3
In another terminal
$ rm /tmp/myfile.txt
Verify the file is 'deleted'
$ lsof | grep myfile
irb 21505 veewee 3r REG 253,0 26 417220 /tmp/myfile.text (deleted)
Step 4
Change to the /proc/<pid>/fd
$ cd /proc/21505/fd
$ ls -l
total 0
lrwx------ 1 veewee veewee 64 Mar 21 23:44 0 -> /dev/pts/0
lrwx------ 1 veewee veewee 64 Mar 21 23:44 1 -> /dev/pts/0
lrwx------ 1 veewee veewee 64 Mar 21 23:44 2 -> /dev/pts/0
lr-x------ 1 veewee veewee 64 Mar 21 23:44 3 -> /tmp/myfile.text (deleted)
Now copy the deleted fd to another location
$ cp 3 /tmp/myfile2.txt
$ cat /tmp/myfile2.text
OMG Please dont delete me
Not something you usually have to do, but could be a life saver.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment