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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.