Bash Shell Environment Variables – Issue an Error When Using Empty Shell Variables

bashenvironment-variablesshell

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?

Best Answer

In POSIX shell, you can use set -u:

#!/bin/sh

set -u
: "${UNSET_VAR}"

or using Parameter Expansion:

: "${UNSET_VAR?Unset variable}"

In your case, you should use :? instead of ? to also fail on set but empty variables:

rm -rf -- "${PROJECT_HOME:?PROJECT_HOME empty or unset}"/*
Related Question