How can I read a sh file while it is working but deleted?

In an interview they asked me this question.

There was an sh file that is already running, but it has been deleted since starting the execution.

They want me to find the process and read the file.

I managed to find the process with

ps -ef | grep test.sh

and tried to read it by using

cat /proc/PID/cmdline test.sh

but it says

no such file or directory

I didn't know what I should do next so I had to skip this.

Maybe it was an easy question but that was really a good question for me and I really want to know the answer. Can you guys help?


Solution 1:

tail -c +0 -f /proc/{pid}/fd/{fd} > /tmp/file

where {pid} is the id of your process and /tmp/file will have its contents. Use another location and name if you want to preserve it.

  • {pid} is the id of the process.
  • {fd} is the file descriptor. lsof should show the fd. lsof is likely also going to show "deleted" on the line so you can grep that too. lsof -nP +L1 will list all files with less than 1 link, a file deleted will have 0. Add a | grep {pid} to search for just your PID.
  • from dessert: lsof -p 22664 | sed -E '$!d;s/.*\s([0-9]+)[a-z]\s.*/\1/' to just get the fd.
  • from comments: you can use less, cat or cp too. I grew up on tail :)