Reputation: 3476
I need to check a lot of environment variables that need to be set in order for my bash script to run. I've seen this question and tried
thisVariableIsSet='123'
variables=(
$thisVariableIsSet
$thisVariableIsNotSet
)
echo "check with if"
# this works
if [[ -z ${thisVariableIsNotSet+x} ]]; then
echo "var is unset";
else
echo "var is set to '$thisVariableIsNotSet'";
fi
echo "check with for loop"
# this does not work
for variable in "${variables[@]}"
do
if [[ -z ${variable+x} ]]; then
echo "var is unset";
else
echo "var is set to '$variable'";
fi
done
The output is:
mles:tmp mles$ ./test.sh
check with if
var is unset
check with for loop
var is set to '123'
If I'm checking the not set variable in an if block, the check works (var is unset
). However in the for loop the if block only prints if a variable is set, not if a variable ist not set.
How can I check variables in a for loop?
Upvotes: 3
Views: 2662
Reputation: 2538
You can try to use indirect expansion ${!var}
:
thisVariableIsSet='123'
variables=(
thisVariableIsSet # no $
thisVariableIsNotSet
)
echo "check with if"
# this works
if [[ -z ${thisVariableIsNotSet+x} ]]; then
echo "var is unset";
else
echo "var is set to '$thisVariableIsNotSet'";
fi
echo "check with for loop"
# this does not work
for variable in "${variables[@]}"
do
if [[ -z ${!variable+x} ]]; then # indirect expansion here
echo "var is unset";
else
echo "var is set to ${!variable}";
fi
done
Output:
check with if
var is unset
check with for loop
var is set to 123
var is unset
Upvotes: 4