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

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

function a {
    # if $1 is set ?
}

当前回答

使用[[-z“$var”]]是了解变量是否已设置的最简单方法,但选项-z无法区分未设置的变量和设置为空字符串的变量:

$ set=''
$ [[ -z "$set" ]] && echo "Set" || echo "Unset" 
Unset
$ [[ -z "$unset" ]] && echo "Set" || echo "Unset"
Unset

最好根据变量的类型进行检查:env变量、参数或常规变量。

对于env变量:

[[ $(env | grep "varname=" | wc -l) -eq 1 ]] && echo "Set" || echo "Unset"

对于参数(例如,检查参数$5的存在):

[[ $# -ge 5 ]] && echo "Set" || echo "Unset"

对于正则变量(使用辅助函数,以优雅的方式实现):

function declare_var {
   declare -p "$1" &> /dev/null
}
declare_var "var_name" && echo "Set" || echo "Unset"

笔记:

$#:提供位置参数的数量。declare-p:提供作为参数传递的变量的定义。如果它存在,则返回0,如果不存在,返回1并打印错误消息。&>/dev/null:在不影响其返回代码的情况下抑制declare-p的输出。

其他回答

如果你和我一样,你所寻找的其实是

“如果设置了变量,bash仅运行命令”

你希望这是一行,所以下面这行是你想要的

仅适用于Bash 4.2或更高版本

仅在设置时运行

if [[ -v mytest ]]; then echo "this runs only if variable is set"; fi

仅在未设置时运行

if [[ ! -v mytest2 ]]; then echo "this runs only if variable is not set"; fi

我的首选方式是:

$ var=10
$ if ! ${var+false};then echo "is set";else echo "NOT set";fi
is set
$ unset -v var
$ if ! ${var+false};then echo "is set";else echo "NOT set";fi
NOT set

因此,基本上,如果一个变量被设置,它就变成了“对结果false的否定”(true=“被设置”)。

并且,如果它未设置,它将变成“对结果true的否定”(因为空结果的求值结果为true)(因此将以false=“NOT set”结束)。

当启用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”模式定义

if [ "$1" != "" ]; then
  echo \$1 is set
else
  echo \$1 is not set
fi

尽管对于参数,通常最好测试$#,我认为这是参数的数量。

if [ $# -gt 0 ]; then
  echo \$1 is set
else
  echo \$1 is not set
fi

要测试是否设置了变量var:[${var+x}]。

若要测试变量是否按名称设置:[${!name+x}]。

要测试是否设置了位置参数:[${N+x}],其中N实际上是一个整数。

这个答案与莱昂内尔的答案几乎相似,但通过省略-z来探索一种更为简约的方法。

要测试是否设置了命名变量,请执行以下操作:

function is_set {
    local v=$1
    echo -n "${v}"
    if [ ${!v+x} ]; then
        echo " = '${!v}'"
    else
        echo " is unset"
    fi
}

要测试是否设置了位置参数:

function a {
    if [ ${1+x} ]; then
        local arg=$1
        echo "a '${arg}'"
    else
        echo "a: arg is unset"
    fi
}

测试表明,不需要特别注意空格和有效的测试表达式。

set -eu

V1=a
V2=
V4=-gt
V5="1 -gt 2"
V6="! -z 1"
V7='$(exit 1)'

is_set V1
is_set V2
is_set V3
is_set V4
is_set V5
is_set V6
is_set V7

a 1
a
a "1 -gt 2"
a 1 -gt 2
$ ./test.sh

V1 = 'a'
V2 = ''
V3 is unset
V4 = '-gt'
V5 = '1 -gt 2'
V6 = '! -z 1'
V7 = '$(exit 1)'
a '1'
a: arg is unset
a '1 -gt 2'
a '1'

最后,请注意set-eu,它保护我们避免常见错误,例如变量名中的拼写错误。我建议使用它,但这意味着未设置的变量和带有空字符串的变量集之间的区别得到了正确处理。