如何在 bash 的 if 块中计算布尔变量?

我定义了以下变量:

myVar=true

现在我想说的是:

if [ myVar ]
then
echo "true"
else
echo "false"
fi

上面的代码可以工作,但是如果我尝试设置

myVar=false

它仍然会输出 true。 有什么问题吗?

编辑: 我知道我可以做一些形式

if [ "$myVar" = "true" ]; then ...

但是有点尴尬。

谢谢

177386 次浏览

bash doesn't know boolean variables, nor does test (which is what gets called when you use [).

A solution would be:

if $myVar ; then ... ; fi

because true and false are commands that return 0 or 1 respectively which is what if expects.

Note that the values are "swapped". The command after if must return 0 on success while 0 means "false" in most programming languages.

SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
(true)    echo "is true";;
(false)   echo "is false";;
(rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.