我如何检查一个变量是否为空的Bash?


当前回答

if [[ "$variable" == "" ]] ...

其他回答

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

如果变量未设置或设置为空字符串(""),则返回true。

if [ -z "$MyVar" ]
then
   echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
   echo "The variable MyVar has something in it."
fi
if [[ "$variable" == "" ]] ...

你可能想要区分未设置变量和已设置且为空的变量:

is_empty() {
    local var_name="$1"
    local var_value="${!var_name}"
    if [[ -v "$var_name" ]]; then
       if [[ -n "$var_value" ]]; then
         echo "set and non-empty"
       else
         echo "set and empty"
       fi
    else
       echo "unset"
    fi
}

str="foo"
empty=""
is_empty str
is_empty empty
is_empty none

结果:

set and non-empty
set and empty
unset

顺便说一句,我建议使用set -u,它会在读取未设置变量时导致错误,这可以避免您发生灾难,如

rm -rf $dir

你可以在这里阅读关于“严格模式”的其他最佳实践。

假设Bash:

var=""
if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi