Saturday, January 24, 2009

rm -rf can't be forgiven

This week, I did a blunder. I did 'rm -rf' on a directory. Can this act be forgiven ? In my case, yes but not all the time. If its not, you qualify for a mention on The Daily WTF. Its because I take regular backups and I use some tools to automatically back up data for me. The reason for writing this post is to make linux users aware of the harm you can do to yourself and the system by issuing a single command.

Lets dig more into some trivial mistakes you can make.
rm -rf * .cpp // Intended to remove all cpp files.
rm -rf / // WTF ?
rm -rf .* // Remove all hidden files

If you are using ext2, recovery is easy. Also, if you want to use any tools for data recovery make sure that you don't write anything to the disk. For safety, unmount all partitions and connect your drive to some other computer and try recovering data. The freed blocks will be the first one to be used by the system so data recovery becomes increasingly difficult the longer the time partition is mounted.

The best option is to use an alias for rm command.
alias rm 'rm -i'

However the -f option will override the alias. Improving it further,
mv /usr/bin/rm /usr/bin/rm.bak


mkdir ~/.Trash &> /dev/null

while [ ! -z "$1" ]; do
mv "$1" ~/.Trash/

You can put a
rm -f ~/.Trash/*
in .logout in home dir. The disadvantage of this approach is, you will become dependent upon this behaviour of "rm", and you will find yourself someday on a normal system where "rm" is really "rm", and you will get yourself in trouble. So its better to define an alias mydelete for 'rm -rf'.

If you have none of the options implemented as described above, you can refer to Recover from rm and Recovering Linux files and filesystems for more info.

1 comment:

Sarath Menon said...

While the script is a good idea, it'll blarf on arguments to rm. IMO, lusers who run rm -rf without thinking deserve to lose their data ;)