Home > Software design >  Parameter expansion for array elements in a loop
Parameter expansion for array elements in a loop

Time:10-04

I am trying to check if all the environment variables are defined.

Test for individual element works fine as defined below:

[ -z ${env_var1: y} ] && echo "Env var not defined."

Although I need to check this for multiple elements, hence want to add it in the loop. But somehow it is not working:

env_var_array=( env_var1 env_var2 env_var3 )
for element in "${env_var_array[@]}"
do
  [ -z ${element: y} ] && echo "$element var not defined."
done

It is not working as expected.

CodePudding user response:

To use variable variable names, use ${!element}:

#!/bin/bash

env_var_array=( env_var1 env_var2 env_var3 )
for element in "${env_var_array[@]}"
do
  [ -z "${!element: y}" ] && echo "$element var not defined."
done
env_var1 var not defined.
env_var2 var not defined.
env_var3 var not defined.

Regarding the : y part:

${parameter: word}

If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
[docs]

Those are not needed in your case, so you can simplfy it to just [ -z ${!element} ]

CodePudding user response:

If all you want to check is that all your environment variables are set, this can be done without a loop like this:

if declare -p "${env_var_array[@]}" >/dev/null 2>&1; then
  printf 'All of these variables are defined: %s\n' "${env_var_array[*]}"
fi
  • Related