1

I have a bash script that runs a check to determine if the requisite environment variables are set before executing its logic.

At the moment I'm repeating the following code block for every environment variable:

if [[ -z "$SOME_ENV_VAR" ]]; then
    echo "Warning - the SOME_ENV_VAR environment variable isn't set"

    exit 1
fi

Is there a way to declare an array and iterate over the array and check if the environment variable is set?

I know how to iterate over arrays in bash, but I'm not sure how to use each iteration variable to check if a similarly named environment variable is present.

1
  • You can use pattern matching. Commented Nov 11, 2019 at 10:01

3 Answers 3

5

You can use indirection to access a variable by its name if that name is stored in another variable. A small example:

x=1
name=x
echo "${!name}" # prints 1

With this approach, you only have to iterate over the names of the variables you want to check:

for name in FIRST_ENV_VAR SECOND_ENV_VAR ...; do
    if [[ -z "${!name}" ]]; then
        echo "Variable $name not set!"
        exit 1
    fi
done

You may also want to use -z "${!name+x}" to accept variables that are set to the empty string, see here.

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

Comments

3
x=(
  LANG
  LC_MEASUREMENT
  LC_PAPER
  LC_MONETARY
  LC_NAME
  LC_ADDRESS
  LC_NUMERIC
  LC_TELEPHONE
  LC_IDENTIFICATION
  LC_TIME
)
for v in "${x[@]}"; do
  echo "$v = \"${!v}\""
done

Result:

LANG = "en_US.UTF-8"
LC_MEASUREMENT = "en_US.UTF-8"
LC_PAPER = "en_US.UTF-8"
LC_MONETARY = "en_US.UTF-8"
LC_NAME = "en_US.UTF-8"
LC_ADDRESS = "en_US.UTF-8"
LC_NUMERIC = "en_US.UTF-8"
LC_TELEPHONE = "en_US.UTF-8"
LC_IDENTIFICATION = "en_US.UTF-8"
LC_TIME = "en_US.UTF-8"

See the bash(1) manual page for an explanation of indirect expansion using ${!name}.

Comments

1

You can create the list of the environment variables you want to iterate over as done in ENV_VAR_ARR.
Then iterate over each of them using a for loop.

The for loop will take each item in the list, assigns it SOME_ENV_VAR and execute the commands between do and done then go back to the top, grab the next item in the list and repeat over.

The list is defined as a series of strings, separated by spaces.

#!/bin/bash

ENV_VAR_ARR='ENV_1 ENV_2 ENV_3'

for SOME_ENV_VAR in $ENV_VAR_ARR
do
    echo $SOME_ENV_VAR
    if [[ -z "${!SOME_ENV_VAR}" ]]; then
        echo "Warning - the $SOME_ENV_VAR environment variable isn't set"
        exit 1
    fi
done

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.