2017-06-21 90 views
3

我需要检查很多需要设置的环境变量,以便运行我的bash脚本。我已经看到了这个question,并试图检查变量是否存在于bash中的for循环中

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块,检查工程(var is unset)。但是,在for循环中,if块只在设置变量时才打印,而不是在变量未设置的情况下打印。

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

回答

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