Iterating over an array of bash variables

I had a requirement for a bash script to check for required variables before running a function. Rather than creating a conditional block for each required variable (or in my case, needing to dynamically change them), let's do something that's more terse and maintainable. The example covers a few bash concepts:

  • Generating an array of variable names
  • Variable name as a string (indirect parameter expansion)
  • Breaking a loop over an array (control flow)
#!/bin/bash

ERROR=0  
declare -a REQUIRED=(  
  "APP_VAR_1" "APP_VAR_2" "APP_VAR_3"
)
for REQ in "${REQUIRED[@]}"  
do  
  if [ -z "${!REQ}" ]; then
    ERROR=1
    printf "\n  - ERROR: ${REQ} undefined.\n\n"
    break
  fi
done

run ()  
{
  printf "\n  - Validated.\n\n"
}

if [ "${ERROR}" == 0 ]; then  
  run
fi  

The ${REQUIRED[@]} syntax sets up the iterable REQ variable. We can access the literal name of the variable with ${REQ} syntax. Whereas, we can access the value of the variable with ${!REQ} indirect parameter expansion. If all the required variables are not -z null, the run() function will continue as expected.