BASH: Checking for environment variables
        Posted  
        
            by Hamza
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Hamza
        
        
        
        Published on 2010-06-05T20:02:10Z
        Indexed on 
            2010/06/05
            20:02 UTC
        
        
        Read the original article
        Hit count: 266
        
Hi folks,
I am trying to check the value of an environment variable and depending on the value do certain things and it works fine as long as the variable is set. When it isn't though I get a whole bunch of errors (as BASH is trying to compare the string I specify with an undefined variable, I guess)
I tried implementing an extra check to prevent it happening but no luck. The block of code I am using is:
#!/bin/bash
if [ -n $TESTVAR ]
then
  if [ $TESTVAR == "x" ]
  then
    echo "foo"
    exit
  elif [ $TESTVAR == "y" ]
  then
    echo "bar"
    exit
  else
    echo "baz"
    exit
  fi
else
  echo -e "TESTVAR not set\n"
fi
And this the output:
$ export TESTVAR=x
$ ./testenv.sh 
foo
$ export TESTVAR=y
$ ./testenv.sh 
bar
$ export TESTVAR=q
$ ./testenv.sh 
baz
$ unset TESTVAR
$ ./testenv.sh 
./testenv.sh: line 5: [: ==: unary operator expected
./testenv.sh: line 9: [: ==: unary operator expected
baz
My question is, shouldn't 'unset TESTVAR' nullify it? It doesn't seem to be the case...
Thanks.
© Stack Overflow or respective owner