Reputation: 39
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
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