gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:50:56 26 4
gpt4 key购买 nike

我需要检查许多需要设置的环境变量,以便我的 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 block 中检查 not set 变量,检查有效(var is unset)。然而,在 for 循环中,if block 仅在设置了变量时打印,如果未设置变量则不打印。

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

最佳答案

可以尝试使用间接扩展${!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

关于bash - 检查bash中的for循环中是否存在变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44677878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com