Bash 为什么这个if语句给了我一个错误

Bash 为什么这个if语句给了我一个错误,bash,shell,Bash,Shell,有人能解释一下为什么这个简单的bash脚本: #!/bin/bash myvar="Hello" if [[ -z "$myvar" ]]; then # echo "It's an unfilled string" else echo "It's a filled string!" fi 告诉我错误 ./testscript: line 7: syntax error near unexpected token `else' ./testscript: line 7: `

有人能解释一下为什么这个简单的bash脚本:

#!/bin/bash

myvar="Hello"

if [[ -z "$myvar" ]]; then
    # echo "It's an unfilled string"
else
    echo "It's a filled string!"
fi
告诉我错误

./testscript: line 7: syntax error near unexpected token `else'
./testscript: line 7: `else'

但是,如果删除回音行上的注释,脚本运行正常。显然,在空if语句中有注释行是有问题的。考虑到这一点,我如何修复它,这样我就可以有一个带注释的空if语句

then
else
之间没有语句,因此这是一个语法错误。如果确实不想在
If
分支中执行任何操作,则可以使用
(或
true
)作为占位符:

#!/bin/bash

myvar="Hello"

if [[ -z "$myvar" ]]; then
    # echo "It's an unfilled string"
    :
else
    echo "It's a filled string!"
fi
更好的是,颠倒你的逻辑:

#!/bin/bash

myvar="Hello"

if [[ -n "$myvar" ]]; then
    echo "It's a filled string!"
fi

这是不使用
if-else
语句的方法

#!/bin/bash

myvar="Hello"

[[ -n "$myvar" ]] && echo "It's a filled string!"
你也可以用这个

#!/bin/bash

myvar="Hello"

[[ -z "$myvar" ]] || echo "It's a filled string!"

echo
应该被注释掉吗?将代码粘贴到@anubhava:你的意思是
?@Cyrus:是的,我的意思是
,但输入错误:)或者-if
[!-z“$myvar”];然后回显“这是一个填充的字符串!”;fi
+1用于复合命令的使用,但如果您解释复合命令可以用作
if。。。然后。。其他的fi