Check if variables exist in for loop in bash
I need to check a lot of environment variables that must be set to run my bash script. I saw 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
Output:
mles:tmp mles$ ./test.sh
check with if
var is unset
check with for loop
var is set to '123'
If I check for an unset variable in the 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 the ist variable is not set.
How can I check variables in a for loop?
+3
source to share
2 answers
You can try using 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
+3
source to share