bash determine if variable is empty and if so exit. bash determine if variable is empty and if so exit. bash bash

bash determine if variable is empty and if so exit.


The answer I prefer is following

[[ -z "$1" ]] && { echo "Parameter 1 is empty" ; exit 1; }

Note, don't forget the ; into the {} after each instruction


One way to check if a variable is empty is:

if [ "$var" = "" ]; then    # $var is emptyfi

Another, shorter alternative is this:

[ "$var" ] || # var is empty


In bash you can use set -u which causes bash to exit on failed parameter expansion.

From bash man (section about set builtin):

-u
Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion. If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status.

For more information I recommend this article: http://redsymbol.net/articles/unofficial-bash-strict-mode/