Best practices to prevent 'rm -rf /' in bash scripts
Solution 1:
alias rm='rm --preserve-root'
IIRC --preserve-root is the default in newer versions of coreutils.
Solution 2:
Always quote your arguments. Even when you know they are sane, it almost never hurts to quote them in scripts.
rm -rf "/$FOO"
will not delete / if $FOO has a leading space, instead you'll just not delete anything. This does require the quotes to be present on the line with rm -rf
, of course, not something like:
TODEL="/$FOO"
rm -rf $TODEL
If you do that, you'll be back in a whole load of trouble.
Also, I tend to think a good ol':
if [ -d "/$FOO" ] ; then
...
fi
(Or -e
if it's just a file) is always a good idea before deleting anything.
Solution 3:
First things first: have backups. :-)
But while I hack up those potentially dangerous scripts, I always first echo the dangerous lines, so I can see what would happen.
You can also add a file named -i
to important directories, so in some situations rm would prompt while trying to remove those. Of course, if you do the deletion via some other method, such as Perl script or even with different rm parameters, that would not help.
It's also possible to set immutable flag to important files and dirs with chattr +i
, but be careful with that one. That can bite you if you actually should remove files from some directory or modify the files ...