RECOVER ACCIDENTALLY DELETED FILES IN LINUX

RECOVER ACCIDENTALLY DELETED FILES IN LINUX

In linux, there are situations where we accidentally delete critical files from the system due to mistakenly executed script. It is often danger to use ‘rm’ command in shell script without proper testing.

If you deleted an active file which is held by processes, then lsof is one way to recover the deleted file immediately before the process is marked for kill

Check lsof to find the deleted file with grep. We will be able to see the deleted text with the process id

[oracle@orcl19x ~]$ lsof | grep -i test

testautop 8754              oracle  255r      REG    8,2        421  39754758 /home/oracle/testautopump.sh (deleted)

In the above output, process id is 8754 and check if the process id file exists in /proc

[oracle@orcl19x ~]$ ls -lrth /proc/8754/fd/255
lr-x------ 1 oracle oinstall 64 Sep  6 16:46 /proc/8754/fd/255 -> /home/oracle/testautopump.sh (deleted)

Copy the process file to the same directory where you deleted or different directory

[oracle@orcl19x ~]$ cp /proc/8754/fd/255 /home/oracle

Check if the copied file exists

[oracle@orcl19x ~]$ ls -lrt /home/oracle
total 12
drwxr-xr-x 3 root   root       35 Feb 28  2021 awscli-bundle
-rw-r--r-- 1 oracle oinstall   58 Sep  6 16:43 expdp.log
-rw------- 1 oracle oinstall   57 Sep  6 16:43 nohup.out
-rwxr-xr-x 1 oracle oinstall 2620 Sep  6 16:50 255

Either copy the file to previous file name or,

[oracle@orcl19x ~]$ cp /proc/8754/fd/255 /home/oracle/255

Move the file to the old name

[oracle@orcl19x ~]$ mv /home/oracle/255 /home/oracle/testautopump.sh

This approach is valid if and only if the process is actively using the deleted and not released. If the process get cleaned up, then this approach is useless which means lsof command will not show any output

Leave a Reply

%d bloggers like this: