Sometimes I use, $PROJECT_HOME/*
to delete all files in the project. When the environment variable, PROJECT_HOME
is not set (because I did su
and the new user doesn't have this environment variable set), it starts deleting all files from the root folder. This is apocalyptic.
How can I configure bash
to throw error, when I use an undefined environment variable in the shell?
set -u
will do what you want. – cuonglm Jun 08 '15 at 06:27[ -z "$PROJECT_HOME" ] || rm -r "$PROJECT_HOME"/*
won't lead to your apocalypse, ever. (set -u
still may). Check out my answer. – Petr Skocik Jun 08 '15 at 07:36[ -z "$VAR" ]
works with an uninitializedVAR
too. The initialization was just to show the undesirable behavior—My point is, if your vars ever do become initialized to empty strings, in whatever way, and you runrm -r "$PROJECT_HOME"/*
mistakenly relying onset -u
, you will get the "apocalyptic" behavior. IHMO, it's better to be safe than sorry when it comes to protecting the entire contents of your computer.set -u
is not safe. – Petr Skocik Jun 08 '15 at 08:00PROJECT_HOME=/etc
? Just checking for an empty value is not enough to prevent cataclysm. You shouldn't use variables from untrusted users when running as root. – Barmar Jun 10 '15 at 19:40