Linux – Best practices to prevent ‘rm -rf /’ in bash scripts

bashlinuxrm

It's well known fact that extra space in env.variable can lead to deletion of / directory in bash script.

#!/bin/bash
...
rm -rf /$MYPATH

if $MYPATH contains values like " dir" or "dir /" it will lead to "rm -rf / dir" or "rm -rf dir /". And will result into "rm -rf /"

Are there any best practices to prevent this situation?

Best Answer

alias rm='rm --preserve-root'

IIRC --preserve-root is the default in newer versions of coreutils.