检查动态变量名称是否存在于bash中

时间:2015-05-13 04:06:34

标签: bash

我希望得到消息“缺少全局变量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

1 个答案:

答案 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