Why is there no such safeguard in the rm command?
There are already three safeguards:
- The
-r
switch, without which a directory can't be removed.
- The
-i
switch, which verifies that you actually want to delete what you've asked to delete. Aliasing rm
to rm -i
turns that safeguard on unless you add the -f
switch to turn it off.
- File ownership, which prevents all users but
root
from deleting the root directory.
The Unix toolset is like a chainsaw: it was designed to do very powerful things and be wielded by people who understand what they're doing. Those who tread carelessly are likely to end up injuring themselves. This isn't to say that the experienced don't make mistakes, and obviously Sun and others feel that users with root
need to be protected from themselves.
However shouldn't this specific case be an exception to that rule?
People have been asking why we can't put a blade guard over the rm
chainsaw since at least the 1980s. (Probably longer, but my history with Unix doesn't go back any further than that.) You have to ask yourself more questions:
Since we're adding exceptions, what else should be considered sacred? Should we prevent recursive deletion of anything in the root directory to avoid equally-devastating mistakes like rm -rf /*
? What about the user's home directory? What about /lib
or /bin
? Would we have to have a special version of rm
to prevent these mistakes on systems with a nontraditional file system layout?
Where do we put the enforcement of these prohibitions? Just in rm
or do we give the kernel that job? Since rm
doesn't actually delete anything (it makes lots of calls to unlink(2)
and rmdir(2)
based on the arguments), there would be no way for the kernel to detect that rm
was really gunning for /
until the moment actually came to delete it. Since the only call to rmdir(2)
that would ever succeed is when the target directory is empty, reaching that point with /
would mean the system's already done for.
The command can brick UEFI devices – Suici Doga – 2016-03-20T10:53:20.130
8I imagine that there is a philosophical bias against it. After all, once you get into the protecting users from themselves business, where should you stop? – dmckee --- ex-moderator kitten – 2011-09-15T12:43:58.627
2Like many, i've done this mistake before now (actually, rm -r $variable/ when $variable turned out to be empty). I put the blame on myself for being stupid, not the o/s for not holding my hand, and i wouldn't want it any other way. – Sirex – 2011-09-15T13:37:13.177
@Sirex I know that situation rather well.
set -u
is your friend. If you setvariable=
though, nothing can save you except defensive programming. – Daniel Beck – 2011-09-15T14:50:05.803What if
rm -rf /
is performed afterchroot
? – mouviciel – 2011-09-15T14:10:53.570