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

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

function a {
    # if $1 is set ?
}

当前回答

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

包括空$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的答案所示,确实是巧合。否则我当然会把它归功于你!

其他回答

case "$1" in
 "") echo "blank";;
 *) echo "set"
esac

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

“如果设置了变量,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
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
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

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

set -o noun set

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