35

So I'm using GNU Screen to manage multiple running scripts/programs. The multiplexing & detachability is quite helpful.

I removed a script from disk and now I'm having some trouble finding the backup. However, one of the terminal sessions was executing the script before the file was deleted and it continues to work just fine.

Is there a way to hijack the terminal session that is currently running the script to recover the contents of this file?

Colt
  • 1,939
  • 6
  • 20
  • 25
Fdo
  • 453
  • 4
  • 6
  • Also: [How to recover deleted file if it is still opened by some process? - SU](https://superuser.com/q/283102/334516), [Relinking a deleted file](https://serverfault.com/q/168909/229499) – muru Jul 21 '17 at 02:06

1 Answers1

61

look for the script's pid using ps

ps -ef|grep script.sh
Fdo  8983  8463  0 12:28 pts/2    00:00:00 /bin/bash ./script.sh

check /proc/$PID/fd/; there should be a broken link to the script file, but cat should work (while the script is running!):

cat /proc/8983/fd/255 
#!/bin/bash
# script contents!

good luck!

Martin Schröder
  • 315
  • 1
  • 5
  • 24
mrc
  • 1,446
  • 11
  • 12
  • @mrc I think that work, because the content of files, is loaded in memory – c4f4t0r Jul 20 '17 at 16:53
  • Great suggestion! Its also a warning that @fdo needs to set up a decent backup routine, because next time he may not be so lucky. – Criggie Jul 20 '17 at 22:11
  • 12
    @c4f4t0r Nothing to do with it being loaded in memory or not. Linux explicitly won't remove a file (inode) while there are open handles - the file remains on the disk, taking up space. `rm` and other tools *unlink* the file, removing the link from the file *name* to the actual data (referenced by inode), but as long as a reference exists (hard link or open handle) the inode is not deleted. – Bob Jul 21 '17 at 00:12
  • Just curious... how did you know to check fd 255? Or is that just an example? – gardenhead Jul 21 '17 at 00:38
  • 2
    @gardenhead It's an example. – user253751 Jul 21 '17 at 01:37
  • @gardenhead, I checked on my machine with a simple script ... – mrc Jul 21 '17 at 07:31
  • This only works if the script was deleted, not if the script was overwritten with rubbish. – Joachim Wagner Sep 11 '19 at 15:53