How to check if an environment variable exists and get its value? [duplicate]
Solution 1:
[ -z "${DEPLOY_ENV}" ]
checks whether DEPLOY_ENV
has length equal to zero. So you could run:
if [[ -z "${DEPLOY_ENV}" ]]; then
MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"
else
MY_SCRIPT_VARIABLE="${DEPLOY_ENV}"
fi
# or using a short-hand version
[[ -z "${DEPLOY_ENV}" ]] && MyVar='default' || MyVar="${DEPLOY_ENV}"
# or even shorter use
MyVar="${DEPLOY_ENV:-default_value}"
Solution 2:
You could just use parameter expansion:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
So try this:
var=${DEPLOY_ENV:-default_value}
There's also the ${parameter-word} form, which substitutes the default value only when parameter is unset (but not when it's null).
To demonstrate the difference between the two:
$ unset DEPLOY_ENV
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' 'default_value'
$ DEPLOY_ENV=
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' ''
Solution 3:
If you don't care about the difference between an unset variable or a variable with an empty value, you can use the default-value parameter expansion:
foo=${DEPLOY_ENV:-default}
If you do care about the difference, drop the colon
foo=${DEPLOY_ENV-default}
You can also use the -v
operator to explicitly test if a parameter is set.
if [[ ! -v DEPLOY_ENV ]]; then
echo "DEPLOY_ENV is not set"
elif [[ -z "$DEPLOY_ENV" ]]; then
echo "DEPLOY_ENV is set to the empty string"
else
echo "DEPLOY_ENV has the value: $DEPLOY_ENV"
fi
Solution 4:
There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.
You can check if a variable is defined:
if [ -z "$a" ]
then
echo "not defined"
else
echo "defined"
fi
and then set a default value for undefined variables or do something else.
The -z
checks for a zero-length (i.e. empty) string. See man bash
and look for the CONDITIONAL EXPRESSIONS section.
You can also use set -u
at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.
Solution 5:
NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
NEW_VAR=${ENV_VAR}
else
NEW_VAR="new value"
fi