如何在shell脚本中检查字符串是否为空?

Bhu*_*esh 3 linux shell shell-script

我有一个这样的脚本

    #!/bin/bash
    line="hello"

    if [ -z $line ] ; then
            echo "String null"
    fi
Run Code Online (Sandbox Code Playgroud)

这将正常工作,但是当我给出line如下

    line="hello welcome"
Run Code Online (Sandbox Code Playgroud)

它将通过错误作为

     a.sh: 5: [: hello: unexpected operator
Run Code Online (Sandbox Code Playgroud)

在那种情况下,我如何检查它是否为 Null ?

小智 11

在 if 条件中,在双引号中给出 $line 它将正常工作

#!/bin/bash
line="hello welcome "

if [ -z "$line" ] ; then
        echo "String null"
fi
Run Code Online (Sandbox Code Playgroud)