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


When I was reading this, I didn't find how to make sure in a loop in bash that every element of a specific list in a variable is effectively reachable (like a path) to make sure it doesn't interrupt a script with -e set?



0


source







All Articles