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
  • 15,050
  • 18
  • 63
  • 96

1 Answers1

9
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
  • 94,503
  • 21
  • 155
  • 181