我希望得到消息“缺少全局变量varB”。
chk_var() {
local n v
for n in varA varB varC; do
eval v=\$$n test -n "$v" && [[ -n $v ]] \
|| echo "Err: missing global variable \$$n"
done
}
varA=3
varB=4
chk_var
答案 0 :(得分:3)
chk_var() {
local n v
for n in varA varB varC; do
if [ -z ${!n+x} ]; then
echo "$n is unset";
else
echo "$n is set to '${!n}'";
fi
done
}
varA=3
varB=4
chk_var
请参阅:How to check if a variable is set in Bash?
!
n
之前的${!n+x}
和${!n}
用于间接访问。
给出:
varA is set to '3'
varB is set to '4'
varC is unset