Checking for environment variables

In Bash (and ksh and zsh), if you use double square brackets you don't need to quote variables to protect against them being null or unset.

$ if [ $xyzzy == "x" ]; then echo "True"; else echo "False"; fi
-bash: [: ==: unary operator expected
False
$ if [[ $xyzzy == "x" ]]; then echo "True"; else echo "False"; fi
False

There are other advantages.


Enclose the variable in double-quotes.

if [ "$TESTVAR" == "foo" ]

if you do that and the variable is empty, the test expands to:

if [ "" == "foo" ]

whereas if you don't quote it, it expands to:

if [  == "foo" ]

which is a syntax error.

Tags:

Linux

Shell

Bash