2

I wish got message "missing global variable 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
Daniel YC Lin
  • 13,229
  • 13
  • 58
  • 83

1 Answers1

7
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

see: How to check if a variable is set in Bash?

the ! before n in ${!n+x} and ${!n} is for indirect access.

Gives:

varA is set to '3'
varB is set to '4'
varC is unset
Community
  • 1
  • 1
perreal
  • 90,214
  • 20
  • 145
  • 172