我如何知道是否在Bash中设置了变量?

例如,如何检查用户是否向函数提供了第一个参数?

function a {
    # if $1 is set ?
}

当前回答

如果您希望测试变量是否绑定或未绑定,即使在启用了nounset选项后,这也能很好地工作:

set -o noun set

if printenv variableName >/dev/null; then
    # variable is bound to a value
else
    # variable is unbound
fi

其他回答

if [[ ${1:+isset} ]]
then echo "It was set and not null." >&2
else echo "It was not set or it was null." >&2
fi

if [[ ${1+isset} ]]
then echo "It was set but might be null." >&2
else echo "It was was not set." >&2
fi

要检查非空/非零字符串变量,即如果已设置,请使用

if [ -n "$1" ]

它与-z相反。我发现自己使用-n多于-z。

您可以像这样使用它:

if [ -n "$1" ]; then
  echo "You supplied the first parameter!"
else
  echo "First parameter not supplied."
fi

用于检查变量是否已声明/未设置的函数

包括空$array=()

以下函数测试给定名称是否作为变量存在

# The first parameter needs to be the name of the variable to be checked.
# (See example below)

var_is_declared() {
    { [[ -n ${!1+anything} ]] || declare -p $1 &>/dev/null;}
}

var_is_unset() {
    { [[ -z ${!1+anything} ]] && ! declare -p $1 &>/dev/null;} 
}

通过首先测试变量是否已(未)设置,可以避免对声明的调用(如果不需要的话)。然而,如果$1包含空$array=()的名称,则调用声明将确保获得正确的结果传递给/dev/null的数据不多,因为只有在变量未设置或为空数组时才会调用declare。

该功能将在以下条件下进行测试:

a、 #未声明a=;#已声明a=“foo”;#已声明a=();#已声明a=(“”);#已声明取消设置a;#未声明a、 #未设置a=;#未设置a=“foo”;#未设置a=();#未设置a=(“”);#未设置取消设置a;#未设置

.

有关详细信息一个测试脚本可以看到我对“如何检查bash中是否存在变量?”问题的回答。备注:declare-p的类似用法,正如Peregring lk的答案所示,确实是巧合。否则我当然会把它归功于你!

当启用Bash选项集-u时,上面的答案不起作用。此外,它们不是动态的,例如,如何测试是否定义了名为“dummy”的变量?试试看:

is_var_defined()
{
    if [ $# -ne 1 ]
    then
        echo "Expected exactly one argument: variable name as string, e.g., 'my_var'"
        exit 1
    fi
    # Tricky.  Since Bash option 'set -u' may be enabled, we cannot directly test if a variable
    # is defined with this construct: [ ! -z "$var" ].  Instead, we must use default value
    # substitution with this construct: [ ! -z "${var:-}" ].  Normally, a default value follows the
    # operator ':-', but here we leave it blank for empty (null) string.  Finally, we need to
    # substitute the text from $1 as 'var'.  This is not allowed directly in Bash with this
    # construct: [ ! -z "${$1:-}" ].  We need to use indirection with eval operator.
    # Example: $1="var"
    # Expansion for eval operator: "[ ! -z \${$1:-} ]" -> "[ ! -z \${var:-} ]"
    # Code  execute: [ ! -z ${var:-} ]
    eval "[ ! -z \${$1:-} ]"
    return $?  # Pedantic.
}

相关:在Bash中,如何测试变量是否以“-u”模式定义

虽然这里所述的大多数技术都是正确的,但Bash 4.2支持对变量的存在进行实际测试(man-Bash),而不是测试变量的值。

[[ -v foo ]]; echo $?
# 1

foo=bar
[[ -v foo ]]; echo $?
# 0

foo=""
[[ -v foo ]]; echo $?
# 0

值得注意的是,与许多其他方法(如使用[-z)不同,这种方法在set-u/set-o nounset模式下用于检查未设置的变量时不会导致错误。