simbro
simbro

Reputation: 3692

How to iterate over array to check list environment variables using Bash?

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.

Upvotes: 1

Views: 4484

Answers (3)

AlexP
AlexP

Reputation: 4430

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

Upvotes: 3

Santosh A
Santosh A

Reputation: 5351

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

Upvotes: 1

Socowi
Socowi

Reputation: 27245

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.

Upvotes: 5

Related Questions