Tuesday, August 09, 2011

How to undelete files from ext3/ext4

Sometimes, especially on the command line, it happens that you delete a file or directory you didn't really plan to delete. A second after hit enter you realize what you have done, maybe you are fast enough to stop the deletion process and save some files, but in the most cases it's already to late, at least for some files.  If you have no or a too old backup you're screwed. 
If you use ext3/ext4 you may be able to recover the file with ext3grep or extundelete with information from the file system journal if the content of the file wasn't already overwritten by new data. 
The first step should be to stop all writing processes on the related partition and unmount that partition as soon as possible. Now you have the choice: if your partition uses ext4 you have to use extundelete, if it's ext3 you can use also ext3grep. Personally, I prefer extundelete, since it supports both file systems and seems on one hand much faster to me than ext3grep and it's also easier to use on the other hand. Due to that, the following examples are for extundelete (you can find a ext3grep How-To here).
If you know the path and the name of the file (let's assume it's /home/tux/cv.tex and /dev/sda4 is mounted to /home) you deleted, switch to root and go to a partition with enough free space to store the deleted files. Then:
# extundelete need the relative file path 
me:/tmp # extundelete --restore-file tux/cv.tex /dev/sda4
As soon as extundelete finished, you'll find the recovered file in /tmp/RECOVERED_FILES/tux/ .
If you deleted more than one file in a directory or a directory itself, you can use --restore-directory :
# extundelete need the relative dir path 
me:/tmp # extundelete --restore-directory tux/Documents/tex/ /dev/sda4
There are some more useful options as --restore-all , --restore-files, --after 'dtime' or --before 'dtime', but in the most cases the two examples above should be enough. You can find both tools in my buildservice repository.

4 comments:

PaweĊ‚ said...

Thanks for this! I didn't it's so easy to do. :)

Anonymous said...

Thank you so much for explaining this. This really saved the day. Recovered some precious things thanks to you.

Anonymous said...

if you don't have a package in your distro's repo and the compilation fails (as for me in opensuse), you migh try with ext4magic. i now have that important text file back :)

if i remember correctly:

ext4magic -R -d /where/to/write/files /dev/partition

and of course: first check with lsof whether there's still a handle open, and all the other tricks. if that doesn't work then the above might work. do this at your own risk ;)

Mark Malakanov said...

Excellent! you saved my day!
I'd add, if it is root FS that is impossible to unmout, one can issue `echo "u" > /proc/sysrq-trigger' to quickly remount all FS to ro. Then `mount -o remount,rw /FS-to-recover-TO'.