Preserve Root Flag for rm Command

Preserve Root Flag for rm Command Preserve Root Flag for rm Command

rm will warn you instead of removing everything in / recursively

rm command, the one used to delete files and directories, can be very dangerous if used with root privileges. It’s comforting to know that most modern rm implementations attempt to help you avoid a complete disaster (of deleting everything on your OS disk).

What preserve-root Flag Does

Default behaviour of rm command in Linux for quite some time, preserve-root flag means that if you attempt to recursively remove the root (/) directory you would get a warning:

greys@stream:/ $ rm -rf /
 rm: it is dangerous to operate recursively on '/'
 rm: use --no-preserve-root to override this failsafe

Why would this be dangerous? Because every directory and filesystem in Unix and Linux is mounted off root (/) path. So if you remove files/directories there recursively, you may wipe out your entire operating system (and quite a bit of mounted filesystems, if your’e really out of luck).

Now, I’m running this command as my own regular user in the example above. So even if rm wasn’t protecting me, I would still be unable to do any real harm to the OS due to core OS files being protected from accidental removal by regular users. But if I was running as root, it would have been really dangerous.

Why preserve-root is Really Useful

Of course, most of us would never consciously attempt removing everything under /, but here’s a very typical scenario that is quite common with beginners: using unitialised variables (empty values).

greys@stream:/ $ MYDIR=mydir
greys@stream:/ $ echo rm -rf /${MYDIR}
rm -rf /mydir
greys@stream:/ $ rm -rf /${MYDIR}

In this example above, I have a variable called MYDIR, which points to a directory. I’m runnign echo command first to verify what rm command will look like – and it seems correct, so I attempt it.

But if I forget to initialise the MYDIR variable, its value will be empty, meaning my command will become much more dangerous:

greys@stream:/ $ MYDIR=
greys@stream:/ $ echo rm -rf /${MYDIR}
rm -rf /
greys@stream:/ $ rm -rf /${MYDIR}
rm: it is dangerous to operate recursively on '/'
rm: use --no-preserve-root to override this failsafe

See Also




Contact Me

Follow me on Facebook, Twitter or Telegram:
Recommended
I learn with Educative: Educative
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!
Recent Articles
03 Sep 2024

macOS Sequoia 15.0

02 Sep 2024

Video: Has This Worked Before?

24 Mar 2024

Homelab: Mac Pro 2013 32GB

Recent Tweets