I've needed to recover deleted files on ext3, FAT, and NTFS file systems in the past, but I recently needed to recover a previous version of a text file I had overwritten by editing and saving it. I initially thought I might be able to recover it either by accessing the inode used by the previous version of the file, or by looking at ext3's journal.
Unfortunately, I had used nano to edit the file. Apparently, nano saves files by truncating and overwriting the file, reusing the same inode. Also, I quickly realized ext3's journal wouldn't help because my file system was mounted using data=ordered, not data=journal. From the ext3 FAQ:
- data=journal: Journals all data and metadata, so data is written twice.
- data=ordered: Only journals metadata changes.
Ultimately, I was able to recover the file with some help from stat, debugfs, and blkls from The Sleuth Kit. Before getting started, you'll need to install The Sleuth Kit. On Debian, it is available as a package, so:
apt-get install sleuthkit
First, check the inode being used by the file:
stat file.txt | grep Inode
This should return a line containing the inode, like:
Next, backup the file, then delete it:
cp file.txt file.old
Run debugfs /dev/sda1, replacing /dev/sda1 with the hard drive the file is on. From the debugfs CLI, run stats and check its output for "Blocks per group". On my system, and most of the time, this is 32768. While still in the debugfs CLI, run imap <inode> to get the block:
imap <1474575>. In my case, the block was 5898242.
Once you know the block the inode is in, and the number of blocks per group, create a block range:
5898242+32768-1 and use blkls to copy the block to a file:
blkls /dev/sda1 5898242-5931009 > tmp.dat
Finally, open tmp.dat in your favorite text editor or use grep to search for the overwritten version of your file.
For more details about ext3 file systems and recovering deleted files: