Is there a way to recover a file that I have deleted but is still open somewhere?
I don't know whether there are any text editors which keep the file opened while you are editing it. Normally (i.e. in Emacs), the file is read into a buffer in RAM and then the file is closed. You edit only in RAM. When you save the buffer, the file is opened, written, and closed again. You can use ps auxw | grep your_editor
to find the PID of your editor, then lsof -p your_PID
to see the files that are still open.
On the other hand, if the file is still in the buffer of your editor, you can just save it.
But that was not your question, so let's pretend you are using cat
as your editor, and the file is really still open:
% cat >the_file.txt
Hello world!
^Z
zsh: suspended cat > the_file.txt
% rm the_file.txt
% ls -l the_file.txt
ls: cannot access the_file.txt: No such file or directory
You can use lsof -n
to see all opened files and grep
to search for your filename.
% lsof -n | grep the_file.txt
cat 2145 elmicha 1w REG 9,1 13 108003357 /home/elmicha/tmp/the_file.txt (deleted)
In the second column you can see the PID of your cat
command. You can change into the corresponding directory in the /proc filesystem, and into the fd
(file descriptor) subdirectory:
% cd /proc/2145/fd
% ls -l
total 0
lrwx------ 1 elmicha elmicha 64 2012-11-07 00:22 0 -> /dev/pts/4
l-wx------ 1 elmicha elmicha 64 2012-11-07 00:22 1 -> /home/elmicha/tmp/the_file.txt (deleted)
lr-x------ 1 elmicha elmicha 64 2012-11-07 00:22 15 -> /proc/4501/auxv
lrwx------ 1 elmicha elmicha 64 2012-11-07 00:22 2 -> /dev/pts/4
Now you can just copy the "file" 1
to another file:
% cp 1 ~/tmp/the_old_file.txt
And see, it's there:
% cat ~/tmp/the_old_file.txt
Hello world!