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

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

function a {
    # if $1 is set ?
}

当前回答

这是我每天使用的:

#
# Check if a variable is set
#   param1  name of the variable
#
function is_set() { [[ $(eval echo "\${${1}+x}") ]]; }

这在Linux和Solaris以及Bash 3.0下运行良好。

$ myvar="TEST"
$ is_set myvar ; echo $?
0

$ myvar=
$ is_set myvar ; echo $?
0

$ unset myvar
$ is_set myvar ; echo $?
1

其他回答

阅读bash手册页的“参数扩展”部分。参数扩展并不能为正在设置的变量提供常规测试,但如果未设置参数,可以对其执行一些操作。

例如:

function a {
    first_arg=${1-foo}
    # rest of the function
}

如果分配了firstarg,则将其设置为等于$1,否则将使用值“foo”。如果绝对必须采用单个参数,并且不存在良好的默认值,则可以在未给定参数时退出并显示错误消息:

function a {
    : ${1?a must take a single argument}
    # rest of the function
}

(注意:作为null命令的用法,它只是扩展其参数的值。在本例中,我们不想对$1做任何操作,如果未设置,只需退出)

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

set -o noun set

if printenv variableName >/dev/null; then
    # variable is bound to a value
else
    # variable is unbound
fi
if [[ ${!xx[@]} ]] ; then echo xx is defined; 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

对于那些希望在使用set-u的脚本中检查未设置或空的脚本:

if [ -z "${var-}" ]; then
   echo "Must provide var environment variable. Exiting...."
   exit 1
fi

常规[-z“$var”]检查将因var而失败;未绑定变量如果设置-u但[-z“${var-}”]如果var未设置而不失败,则扩展为空字符串。