Wednesday, May 1, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 1360  / 2 Years ago, sat, september 3, 2022, 5:00:06

This question is related to How to recover deleted files? but it is slightly different in nature.



Suppose I have a file named ~/something open in a text editor. Further suppose that I open a terminal and run the following command while the file is still open in the text editor:



rm ~/something


This will delete the file. Now suppose that I changed my mind and wanted to get the file back. The file is still open in the text editor, so it hasn't been removed from the disk or filesystem yet.



Is there any way to recover it?


More From » delete

 Answers
2

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!

[#34431] Saturday, September 3, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
etzelmortg

Total Points: 430
Total Questions: 105
Total Answers: 106

Location: Suriname
Member since Sun, Jun 13, 2021
3 Years ago
;