AtomEye
AtomEye

Reputation: 91

Bash check environment variables are set in an array of env vars

I have an array of environment variables, and want to check each env var to ensure they are set. I'm trying to use an array b/c I'm going to have around 30 env vars to check. If I don't use the for loop and only the if statement, the script works. Unfortunately, I don't want 30 separate if statements.

Am I going about this the wrong way?

# my array to store env vars
env_vars=("A" "B" "C")

export A=10
export B=test
export C=

for each in ${env_vars[@]}; do 
    echo $each # this works fine
    if [ -z "$each" ]; then # this line doesn't seem to work
        echo $each;
        exit 1
    fi
done

Upvotes: 2

Views: 2678

Answers (1)

chepner
chepner

Reputation: 532448

bash has an operator for this: -v. (I'm ignoring the distinction between environment variables and shell variables for the moment.)

for each in "${env_vars[@]}"; do
    if ! [[ -v $each ]]; then
        echo "$each is not defined"
        exit 1
    fi
done

Your [ -z "$each" ] is just testing if the value of $each (that is, the name of the variable stored in env_var) is empty, which it clearly is not; it was just assigned a name! You want to see if the variable named in each is defined, which is what -v is for.

Without support for -v, you can use the following construct:

for each in "${env_vars[@]}"; do
    if [ -z "${!each+x}" ]; then
        echo "$each is not defined"
        exit 1
    fi
done

However, there is something to be said for some repetition, when it makes your code clearer. Something like

: ${A?A not set}
: ${B?B not set}
: ${C?C not set}

will work in any POSIX shell and is more straightforward than a loop requiring bash extensions like indirection parameter expansion or the -v operator.

Upvotes: 7

Related Questions