检查环境变量

我试图检查一个环境变量的值,根据这个值做一些特定的事情,只要设置了变量,就可以正常工作。如果不是这样,我会得到一大堆错误(我猜是因为 BASH 试图将我指定的字符串与未定义的变量进行比较)

我尝试执行一个额外的检查,以防止这种情况发生,但没有运气。我使用的代码块是:

#!/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

这是输出:

$ 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

我的问题是,“未设置 TESTVAR”不应该使它无效吗? 似乎不是这样的..。

130958 次浏览

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 the parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

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

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

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 ]]