Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for environment variables

Tags:

linux

bash

shell

People also ask

How do I get a list of environment variables?

You can open a Command Prompt, type set , and press Enter to display all current environment variables on your PC. You can open PowerShell, type Get-ChildItem Env: , and press Enter to display all current environment variables on your PC.

What command shows environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables. To reference a variable, use $varname , with a prefix '$' (Windows uses %varname% ).


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.


Look at the section titled "Parameter Expansion" you'll find things like:

${parameter:-word}
Use Default Values. If parameter is unset or null, the expan‐ sion of word is substituted. Otherwise, the value of parameter is substituted.


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.


Your test to see if the value is set

if [ -n $TESTVAR ]

actually just tests to see if the value is set to something other than an empty string. Observe:

$ unset asdf
$ [ -n $asdf ]; echo $?
0
$ [ -n "" ]; echo $?
1
$ [ -n "asdf" ]; echo $?
0

Remember that 0 means True.

If you don't need compatibility with the original Bourne shell, you can just change that initial comparison to

if [[ $TESTVAR ]]

After interpretation of the missing TESTVAR you are evaluating [ == "y" ]. Try any of:

 "$TESTVAR"
 X$TESTVAR == Xy
 ${TESTVAR:-''}