使用函数检查 bash 环境变量是否存在

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}" ]]; thenif [[ -z "${$1}" ]]; then这些都不起作用。

anu*_*ava 5

您可以使用这个功能:

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

代码演示

  • 如果您的 bash 版本支持它(我相信是 4.4 或更高版本),您也可以使用 [[ ${!1@a} = *x* ]]` 。(“${...@a}”运算符扩展为变量属性,而不是其值。)需要间接扩展来从“$1”获取名称,而不是检查“$1”的属性。 (2认同)

Jet*_*sel 3

您可以使用-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)

只需替换exitreturn,否则您的交互式会话将立即退出。

然后获取该 rcfile。

source ~/.profile 
Run Code Online (Sandbox Code Playgroud)

假设~/.profile是该函数所在的位置。

您可以在交互式会话期间进行测试。

checkForVariable ENVIRONMENT_NAME
Run Code Online (Sandbox Code Playgroud)

编辑:正如 chepner 所指出的,我已经添加了该-x属性的测试。

  • 这不区分常规 shell 变量和环境变量。您还需要检查名称上的“-x”属性。 (3认同)