检查bash中的for循环中是否存在变量

时间:2017-06-21 13:42:06

标签: bash

我需要检查一些需要设置的环境变量才能运行我的bash脚本。我已经看过question并试过了

thisVariableIsSet='123'

variables=(
  $thisVariableIsSet
  $thisVariableIsNotSet
)

echo "check with if"

# this works
if [[ -z ${thisVariableIsNotSet+x} ]]; then
  echo "var is unset";
else
  echo "var is set to '$thisVariableIsNotSet'";
fi

echo "check with for loop"

# this does not work
for variable in "${variables[@]}"
do
  if [[ -z ${variable+x} ]]; then
    echo "var is unset";
  else
    echo "var is set to '$variable'";
  fi
done

输出结果为:

mles:tmp mles$ ./test.sh 
check with if
var is unset
check with for loop
var is set to '123'

如果我正在检查if块中的not set变量,则检查有效(var is unset)。但是在for循环中if块仅在设置变量时打印,而不是在未设置变量的情况下打印。

如何检查for循环中的变量?

1 个答案:

答案 0 :(得分:3)

您可以尝试使用间接展开${!var}

thisVariableIsSet='123'

variables=(
  thisVariableIsSet  # no $
  thisVariableIsNotSet
)

echo "check with if"

# this works
if [[ -z ${thisVariableIsNotSet+x} ]]; then
  echo "var is unset";
else
  echo "var is set to '$thisVariableIsNotSet'";
fi

echo "check with for loop"

# this does not work
for variable in "${variables[@]}"
do
  if [[ -z ${!variable+x} ]]; then   # indirect expansion here
    echo "var is unset";
  else
    echo "var is set to ${!variable}";
  fi
done

输出:

check with if
var is unset
check with for loop
var is set to 123
var is unset