Nicolas El Khoury Nicolas El Khoury - 1 year ago 181
Bash Question

shell script: how to check if an environment variable exists, and get its value?

I am writing a shell script. In this shell script, I am have a variable that either takes a default value, or the value of an environment variable. However, the environment variable doesn't have to be present.

For instance, assume, before running the script, I perform the following operation:

export DEPLOY_ENV=dev

How do I tell the script to search for this environment variable, and store its value in a variable inside the script. Moreover, how do I tell the script that if this environment variable does not exist, store a default variable?

Answer Source
if [[ -z "${DEPLOY_ENV}" ]]; then
  MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"

# or using a short-hand version

[[ -z "${DEPLOY_ENV}" ]] && MyVar='default' || MyVar="${DEPLOY_ENV}"

# or even shorter use

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download