我如何知道是否在Bash中设置了变量?
例如,如何检查用户是否向函数提供了第一个参数?
function a {
# if $1 is set ?
}
我如何知道是否在Bash中设置了变量?
例如,如何检查用户是否向函数提供了第一个参数?
function a {
# if $1 is set ?
}
当前回答
略读所有答案后,这同样有效:
if [[ -z $SOME_VAR ]]; then read -p "Enter a value for SOME_VAR: " SOME_VAR; fi
echo "SOME_VAR=$SOME_VAR"
如果您不使用SOME_VAR代替我的$SOME_VVAR,它会将其设置为空值;$这是工作所必需的。
其他回答
我总是使用这个,因为任何第一次看到代码的人都很容易理解:
if [ "$variable" = "" ]
then
echo "Variable X is empty"
fi
如果要检查是否为空;
if [ ! "$variable" = "" ]
then
echo "Variable X is not empty"
fi
就是这样。
在现代版本的Bash(我认为是4.2或更高版本;我不确定)上,我会这样做:
if [ ! -v SOMEVARIABLE ] #note the lack of a $ sigil
then
echo "Variable is unset"
elif [ -z "$SOMEVARIABLE" ]
then
echo "Variable is set to an empty string"
else
echo "Variable is set to some string"
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
这是我每天使用的:
#
# 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
如果您希望测试变量是否绑定或未绑定,即使在启用了nounset选项后,这也能很好地工作:
set -o noun set
if printenv variableName >/dev/null; then
# variable is bound to a value
else
# variable is unbound
fi