0

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.

disp_name
  • 1,448
  • 2
  • 20
  • 46
  • By construction, `element` in your code is one of the strings _env_var1_ and so on. Of course `$element` is always defined. Hence `${elements:+y} always expands to _y_. But in any case: You ask for testing the existence of **environment** variables only, but your code seems to be targeted to **any** bash variable, irrespective whether or not it is in the environment. I think you should clarify this point. – user1934428 Oct 04 '21 at 12:15

2 Answers2

2

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} ]

0stone0
  • 34,288
  • 4
  • 39
  • 64
0

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41