我如何知道是否在Bash中设置了变量?
例如,如何检查用户是否向函数提供了第一个参数?
function a {
# if $1 is set ?
}
我如何知道是否在Bash中设置了变量?
例如,如何检查用户是否向函数提供了第一个参数?
function a {
# if $1 is set ?
}
当前回答
阅读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做任何操作,如果未设置,只需退出)
其他回答
如果你想检查$@中的任何内容,我找到了一个更好的代码。
if [[ $1 = "" ]] then echo '$1 is blank' else echo '$1 is filled up' fi
为什么会这样?$@中的所有内容都存在于Bash中,但默认情况下为空,因此test-z和test-n无法帮助您。
更新:您还可以计算参数中的字符数。
if [ ${#1} = 0 ] then echo '$1 is blank' else echo '$1 is filled up' fi
对于那些希望在使用set-u的脚本中检查未设置或空的脚本:
if [ -z "${var-}" ]; then
echo "Must provide var environment variable. Exiting...."
exit 1
fi
常规[-z“$var”]检查将因var而失败;未绑定变量如果设置-u但[-z“${var-}”]如果var未设置而不失败,则扩展为空字符串。
这是我每天使用的:
#
# 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
为了明确回答OP关于如何确定变量是否已设置的问题,Lionel的回答是正确的:
if test "${name+x}"; then
echo 'name is set'
else
echo 'name is not set'
fi
这个问题已经有很多答案,但没有一个提供真正的布尔表达式来明确区分变量值。
以下是我得出的一些明确表达:
+-----------------------+-------------+---------+------------+
| Expression in script | name='fish' | name='' | unset name |
+-----------------------+-------------+---------+------------+
| test "$name" | TRUE | f | f |
| test -n "$name" | TRUE | f | f |
| test ! -z "$name" | TRUE | f | f |
| test ! "${name-x}" | f | TRUE | f |
| test ! "${name+x}" | f | f | TRUE |
+-----------------------+-------------+---------+------------+
顺便说一下,这些表达式是等价的:测试<表达式><=>〔<表达式>〕
其他需谨慎使用的歧义表达:
+----------------------+-------------+---------+------------+
| Expression in script | name='fish' | name='' | unset name |
+----------------------+-------------+---------+------------+
| test "${name+x}" | TRUE | TRUE | f |
| test "${name-x}" | TRUE | f | TRUE |
| test -z "$name" | f | TRUE | TRUE |
| test ! "$name" | f | TRUE | TRUE |
| test ! -n "$name" | f | TRUE | TRUE |
| test "$name" = '' | f | TRUE | TRUE |
+----------------------+-------------+---------+------------+
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