如何检查环境变量是否存在并获取其值? [英] How to check if an environment variable exists and get its value?
问题描述
我正在编写一个shell脚本.在此Shell脚本中,我有一个采用默认值或环境变量值的变量.但是,不必存在环境变量.
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?
推荐答案
[ -z "${DEPLOY_ENV}" ]
检查DEPLOY_ENV
的长度是否等于零.这样就可以运行:
[ -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}"
这篇关于如何检查环境变量是否存在并获取其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!