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.
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 .
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 }
.
declare -a MY_ENVS
# Set the above array with whatever
# env variables you want to check
# e.g.,
MY_ENVS+=( "HOME" )
Loop through all of them,
for env_var in "${MY_ENVS[@]}"
do
if [ -z "${env_var}" ]
then
echo "${env_var} not set"
fi
done
Or in case you want to store values corresponding to particular env vars, use associative arrays:
declare -A ENV_VARS_A
ENV_VARS_A["HOME"]="some val"
Iteration:
for env_var in "${!ENV_VARS_A[@]}"
do
# env_var is key
:
done
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.