2017-06-21 141 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