Disclaimer

The views and opinions expressed in this blog are my own and do not necessarily reflect those of my employer. The views and opinions expressed by visitors to this blog are theirs and do not necessarily reflect my own

Friday, February 02, 2007

Un-deleting Files on Linux

Ever deleted a file from a terminal session in linux and wished you hadn't. Yeah, its happened to me too. Good news, if your using ext2, or ext3 as your file system and you set your system up properly. I.E you created separate partitions for each mount point, e.g. /, /home, /opt etc. You need to just unmount the volume where the file was located e.g. /home and use Midnight Commander (mc) to get your file back. mc comes standard with most distributions but if it doesn't go to http://www.gnome.org/mc/ and grab a copy. First unmount the volume eg.
umount /dev/sdd1

Inside mc, type:

cd undel:/dev/sdd1
You can't do this anywhere else but mc. Using the "cd" command in mc normally does what it would at a shell prompt; it changes directories. This special syntax instructs mc to display all the undeleted files on that partition instead of the files in a directory.
Wait a moment while it searches through that ext2 filesystem for delete inodes (an inode holds the _contents_ of a file, but not the directory name, etc.). In a minute or so, you'll see a list of files with names like "23434632:2" in that window. The dates and times for the entries are the dates and times when that inode was deleted. I find it most useful to sort this window according to time:
[F9], r, s, m, [Enter]
or
[F9], l, s, m, [Enter]
You can use the [F3] "View" feature to look at the contents of the inode. Press on top of the files that have times around the time you think you deleted the file(s). This tags them to be undeleted in a moment. In the other window (use [tab] to switch windows in mc), make an empty directory under /tmp, such as /tmp/deletedfiles.
mkdir /tmp/deletedfiles
Now switch back to your undel window and press [F5] to copy those files to your real filesystem. If you're done, you can leave mc with the key - see the legend at the bottom of the screen.

This would also be a good time to remount the /home partition with

mount /home
At this point you'll probably want to look at each one and decide what the real name should be. Recovered files should now show in /tmp/deletedfiles. Interact with these as you would any other file. Adapted from an article found here