Bash函数检查是否设置了给定变量

问题描述:

此答案中所述,检查bash中是否设置了变量的正确"方法如下所示::

As explained in this answer, the "right" way to check if a variable is set in bash looks like this:

if [ -z ${var+x} ]; then
    echo "var is unset"
else
    echo "var is set to '$var'"
fi

我感兴趣的是如何将其提取到可用于不同变量的函数中.

What I'm interested in is how to extract this into a function that can be reused for different variables.

到目前为止,我能做的最好的事情是:

The best I've been able to do so far is:

is_set() {
  local test_start='[ ! -z ${'
  local test_end='+x} ]'
  local tester=$test_start$1$test_end

  eval $tester
}

这似乎可行,但是有没有更好的方法而不是调用 eval ?

It seems to work, but is there a better way that doesn't resort to calling eval?

在Bash中,您可以使用 [[--v var]] .不需要功能或复杂的方案.

In Bash you can use [[ -v var ]]. There's no need for a function or convoluted schemes.

从联机帮助页:

   -v varname
          True if the shell variable varname is set (has been assigned a value).

前2个命令序列显示 ok :

[[ -v PATH ]] && echo ok

var="" ; [[ -v var ]] && echo ok

unset var ; [[ -v var ]] && echo ok