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

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

function a {
    # if $1 is set ?
}

当前回答

在现代版本的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

其他回答

在现代版本的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 [[ ${!xx[@]} ]] ; then echo xx is defined; fi

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

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

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

略读所有答案后,这同样有效:

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,它会将其设置为空值;$这是工作所必需的。

您可以执行以下操作:

function a {
        if [ ! -z "$1" ]; then
                echo '$1 is set'
        fi
}