daveoman
daveoman

Reputation: 39

Test if environment variables inside a list exist (hush shell)

I've seen a ton of "how to test is an environment variable exists". And, it looks like the best answer is something like [ -z ${var+x} ]

That's all great, but what if I have a list of possible environment variables inside of a for loop like:

MY_LIST="a b c d e f g"

and I want to actually see if $a, $b, $c, etc., exist? As in, were they set in the passed in environment.

Tried:

for i in $MY_LIST; do  
 if [ -z ${$i+x} ]; then  
  echo "doesn't exist"  
 else  
  echo "does exist"  
 fi  
done  

to no avail. What's the trick? Note I'm in the hush shell.

Upvotes: 0

Views: 540

Answers (1)

Barmar
Barmar

Reputation: 781706

You need to use indirect expansion when the name of the variable is in another variable. You do this by putting ! at the beginning of the variable name.

for i in $MY_LIST; do  
   if [ -z ${!i+x} ]; then  
      echo "doesn't exist"  
   else  
      echo "does exist"  
   fi  
done  

Upvotes: 2

Related Questions