How to prevent accidentally doing "rm -rf /" | How to Install safe-rm

As a server administrator, I rely mostly on root or sudo access--allowing me absolute control of the server. However, "with great power, comes great responsibility!"

You can easily accidentally do this devastatingly bad command of wiping your entire system clean.

rm -rf /
# or
rm -rf /*

Which looks almost identical to the popular command

rm -rf ./
# or
rm -rf ./*

There was a recent prank on 4chan /b/ forum that, in short, instructed users to execute the above command in order to "unlock Apple OS X bitcoin mining". 

4Chan Apple computer unlock bitcoin prank

LOL... Anyhow...

The fix

Replace rm with safe-rm--this basically prevents your from doing destructive commands as shown above...

cd /usr/local/src
# Find the latest version here: https://launchpad.net/safe-rm/+download​
wget https://launchpad.net/safe-rm/trunk/0.10/+download/safe-rm-0.10.tar.gz
tar xvf safe-rm-0.10.tar.gz
cd safe-rm-0.10

Locate rm

find / -name "rm"

I get this: /bin/rm . We'll use this example for the instructions below. 

Next, we echo our environment $PATH, so we can see the path order which our system's binaries are being searched for and executed. 

echo $PATH

Gives me the following; this varies accordingly:

/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

So looking at the paths above, /usr/local/sbin path gets processed first, /usr/local/bin second, /sbin third, and /bin (location of our rm) forth, etc .

This is KEY: We need to place our safe-rm in any of the paths BEFORE the path where rm is located; i.e. any of the first 3 paths, which are before /bin

mv safe-rm /usr/local/sbin​/rm

And that should do it.

You can add your custom location by including them in /etc/safe-rm.conf; example:

vi /etc/safe-rm.conf 
# Put whatever locations you want
/home/USER/public_html
/backup
/private

But by default, safe-rm protects most the usual suspects:

/bin               
/boot 
/dev
/etc
/home
/initrd
/lib 
/lib32
/lib64
/proc
/root 
/sbin
/sys
/usr
/usr/bin
/usr/include
/usr/lib
/usr/local
/usr/local/bin
/usr/local/include
/usr/local/sbin
/usr/local/share
/usr/sbin
/usr/share
/usr/src
/var  

Troubleshooting

If your rm is located in the first environment path, then we have to move it to another path after this one.

For example: Say our rm is located in the first path /usr/local/sbin. We then have to move rm from that path and into a subsequent one, and place safe-rm in a path BEFORE the path where we move rm to.

cp -a /usr/local/sbin/rm /sbin
​mv /usr/local/sbin/rm /usr/local/sbin/rm-01
​cp safe-rm /usr/local/sbin/rm
Tags: Linux rm safe-rm Administration