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.

1
  • 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. Commented Oct 4, 2021 at 12:15

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.