How to recover Deleted Files With lsof

Accidentally deleted files are easily recovered with lsof.

For example, if you just deleted a file /var/lib/mysql/ib_logfile1 and you now want to recover it.

A file in Linux is a pointer to an inode, which contains the file data (permissions, owner and where its actual content lives on the disk). Deleting the file removes the link, but not the inode itself – if another process has it open, the inode isn't released for writing until that process is done with it.


/usr/sbin/lsof | grep ib_logfile1

or 

lsof | grep deleted

to list those deleted files.


mysqld     6355     mysql   10uW     REG               8,17    268435456         18 /var/lib/mysql/ib_logfile1 (deleted)

The important columns are the second one, which gives you the PID of the process that has the file open (6355), and the fourth one, which gives you the file descriptor (10). Now, we go look in /proc, where there will still be a reference to the inode, from which you can copy the file back out:

ls -l /proc/6355/fd/10
lrwx------ 1 root root 64 Mar 12 15:50 /proc/6355/fd/10 -> /var/lib/mysql/ib_logfile1 (deleted)

cp /proc/6355/fd/10 /var/lib/mysql/ib_logfile1.bak

Note: don't use the -a flag with cp, as this will copy the (broken) symbolic link, rather than the actual file contents.

Comments

Popular posts from this blog

Check MySQL query history from command line