Bash – How to avoid rm -rf /

I am brushing up on my bash scripting skills, as I’ve only learned bash through trial and error as well as stealing code found on the Internet. Something simple that I came across is preventing unintentional file/folder removals such as the classic “rm -rf /” which will delete the entire file system in some cases. In the following example we use “unset” to remove the value of the variable “rmFile” which contains the filename that we want to delete. This will simulate what will happen if we don’t validate the variables in the “rm” command first:

Running the “rm -rf $HOME$rmFile” command in the above example would delete the home directory of the user:
5-25-2016 6-28-07 PM

This can easily be avoided by checking that the variables we want to use for the “rm” command actually has a value before we execute. We can check this using “if [ -n $variable ]; then” as seen in this example:

5-25-2016 6-32-39 PM

Luckily the “if” statement detected that we were about to do something unintended and exited instead. If we comment out lineĀ 4 the variable has a proper value and the “rm” command executes as expected:5-25-2016 6-33-56 PM