Tuesday, November 22, 2011

Recover deleted file on Linux


If you deleted a file on linux based OS accidentally, and want to recover it, lsof command may help you.

lsof is a Linux tool which can show open files and network connections, and even recover deleted files.

If you have ever deleted a file by mistake; been clearing up log files, or just used rm without thinking, there is a way of recovering that deleted file. For example, to recover a missing access_log used by Apache you can search for it via this command:

$ lsof | grep access_log

which output will be similar to:

httpd 26120 apache 42w REG 253,0 5852 12222531 /apachelogs/access_log (deleted)

The key word to look for here is deleted in brackets. The good news is a process (26120) still has the file open and without this process keeping the file open we would have lost the file permanently. So, with the Apache daemon helping us out we can view the missing info by looking inside the proc filesystem, the process id (26120), and finally in the file descriptor (fd):

$ cat /proc/26120/fd/42

This outputs the contents of my deleted access_log which shows the data is still there. All you need to do now is simply redirect the contents back to /apachelogs/access_log, like this:

$ cat /proc/26120/fd/42 > /apachelogs/access_log

Now you have recovered your access_log with all the data back to its original location. (You should also restart Apache). lsof can do much more, however, this is one example which could save the day.

Feel free to share other useful example of lsof here (in comments).

5 comments:

Vishal Raj said...

But what if the file is not being held back by an process? Does that means file has been lost permanently?

Vishnu Agarwal said...

@vishal If file is held by a process, then its recovery is 100% guaranteed & simple.
However, If it is not, still file is not lost permanently. Before the shutdown, if that memory block is not overwritten, there are some chances of recovery.

Let me know if you come across some of the tool / utility or set of commands.

Nishant said...

I just created a linux file and then deleted it and then used lsof command. It did not give any output.
gvim aaa

rm aaa
lsof | grep aaa


This did not give any output

Vishnu Agarwal said...

Hi Nishant,
Thanks for trying your hands on it.

As Discuss in my previous comment as well, If file is held by a process, then its recovery is 100% guaranteed & simple.

However, I believe the file you created, no process was holding it, so pointer was released and lsof (list of open files) command didn't give any output.

Try to delete e.g. access_log while apache is running, and follow the steps.

Contact me in case you need more insight in that. I can give you more examples.

Regards,
Vishnu Agarwal

arumugam said...
This comment has been removed by a blog administrator.

LinkWithin

Related Posts with Thumbnails