Gri*_*der 5 bash environment-variables
这可能已经在其他帖子中得到了回答,但我认为我无法准确找到我正在寻找的内容。
我有一个 ( #!/usr/bin/env bash) 函数来检查(环境)变量是否存在
checkForVariable() {
if [[ -z $1 ]]; then
echo "Error: Define $1 environment variable"
exit 1
fi
}
Run Code Online (Sandbox Code Playgroud)
但在错误消息中我希望它告诉我缺少哪个环境变量。
如果我用它来称呼它
checkForVariable "${ENVIRONMENT_NAME}"
如果ENVIRONMENT_NAME没有设置,那么显然我会得到Error: Define environment variable这是没有用的。
如何更改我的函数,以便我可以传递checkForVariable字符串而不是变量引用,即
checkForVariable "ENVIRONMENT_NAME"
我试过例如。if [[ -z "\$${1}" ]]; then但if [[ -z "${$1}" ]]; then这些都不起作用。
您可以使用这个功能:
checkForVariable() {
if [[ -z ${!1+set} ]]; then
echo "Error: Define $1 environment variable"
exit 1
fi
}
Run Code Online (Sandbox Code Playgroud)
然后将其用作:
checkForVariable ENVIRONMENT_NAME
Run Code Online (Sandbox Code Playgroud)
请注意,在函数${!1+set}中使用给定名称取消引用变量并需要检查以检查设置为空值的环境变量。$1:+set
您可以使用-v并使用 来否定它!,并且对属性进行测试-x而不是-z
checkForVariable() {
local env_var=
env_var=$(declare -p "$1")
if ! [[ -v $1 && $env_var =~ ^declare\ -x ]]; then
echo "Error: Define $1 environment variable"
exit 1
fi
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在脚本内进行测试。
checkForVariable ENVIRONMENT_NAME
Run Code Online (Sandbox Code Playgroud)
这是根据帮助测试的。
help test | grep -- '^[[:space:]]*-v'
Run Code Online (Sandbox Code Playgroud)
输出
-v VAR True if the shell variable VAR is set.
Run Code Online (Sandbox Code Playgroud)
还有!
help test | grep -- '^[[:space:]]*!'
Run Code Online (Sandbox Code Playgroud)
输出
! EXPR True if expr is false.
Run Code Online (Sandbox Code Playgroud)
-x此外,对于切普纳指出的环境变量,有必要通过测试输出来查找属性declare -p ENV_NAME
help declare | grep -- '^[[:space:]]*-x'
Run Code Online (Sandbox Code Playgroud)
输出
-x to make NAMEs export
Run Code Online (Sandbox Code Playgroud)
尽管如果您在脚本本身而不是在交互式 shell 中测试变量,则上述方法有效。现在,如果您想在交互式会话中执行此操作,则需要获取文件/脚本才能使其工作。
将其放入您的 中dotfiles / rcfiles,例如~/.profileor~/.bash_profile或~/.bashrc
checkForVariable() {
local env_var=
env_var=$(declare -p "$1")
if ! [[ -v $1 && $env_var =~ ^declare\ -x ]]; then
echo "Error: Define $1 environment variable"
return 1
fi
}
Run Code Online (Sandbox Code Playgroud)
只需替换exit为return,否则您的交互式会话将立即退出。
然后获取该 rcfile。
source ~/.profile
Run Code Online (Sandbox Code Playgroud)
假设~/.profile是该函数所在的位置。
您可以在交互式会话期间进行测试。
checkForVariable ENVIRONMENT_NAME
Run Code Online (Sandbox Code Playgroud)
编辑:正如 chepner 所指出的,我已经添加了该-x属性的测试。
在 GNU Linux 和 FreeBSD 上测试。