Check ENV variables in a loop to see if they were set

Viewed 22

Thought it was a simple thing, but not sure why it got messed up I'm trying in a for-loop to check a few ENV variables and make sure they were set.

This is the current code

# Bash 4.2 ( not 4.4 )
# Verify ENV
declare -a env_vars=(
    "HOME",
    "PATH",
    "PYTHONPATH",
    "TESTNONEXISTING"
)
for evar in "${env_vars[@]}"; do
    # Tried: printenv
    # Tried: -v $evar
    # Tried: eval
    if [[ -z "${evar}" ]]; then
        echo
        echo "ERROR: ENV var '$evar' is missing"        
        echo
        exit 1
    fi
done

I tried many things suggested here in StackOverflow - but they don't work when used in a loop ( as a string )

An example of something that works, but it's useless ...

required_env () {
    ename=$1
    evalue=$2
    
    if [[ -z "$evalue" ]]; then
        echo "ENV variable '$ename' is missing"
        exit 1
    else
        echo "Variable exists"
    fi
}

required_env "HOME" $HOME
required_env "PATH" $PATH
etc ...

The problem is mainly - how to convert a string - to a real variable inside the "if" - that's what I cannot get .. Any suggestions ?

1 Answers

-z tests if the string is not empty. On the first iteration evar=HOME, sp [[ -z "${evar}" ]] becomes [[ -z "HOME" ]]. You are checking if the name of the variable is not empty, not the value of the variable.

You can just check if a variable is set with -v.

[[ -v "$evar" ]]

Note that there is a difference between unset and (set and empty) and (set and not-empty). -z checks for unset or (set and empty).

how to convert a string - to a real variable inside the "if"

Use variable indirection.

[[ -z "${!evar}" ]]
Related