bash 如何在bash中的if块中评估布尔变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3810709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:42:02  来源:igfitidea点击:

How to evaluate a boolean variable in an if block in bash?

bash

提问by devoured elysium

I have defined the following variable:

我定义了以下变量:

myVar=true

now I'd like to run something along the lines of this:

现在我想按照以下方式运行一些东西:

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

The above code does work, but if I try to set

上面的代码确实有效,但是如果我尝试设置

myVar=false

it will still output true. What might be the problem?

它仍然会输出true。可能是什么问题?

edit: I know I can do something of the form

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

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

but it is kinda awkward.

但这有点尴尬。

Thanks

谢谢

回答by Aaron Digulla

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

bash 不知道布尔变量,也不知道test(这就是您使用时调用的[)。

A solution would be:

一个解决方案是:

if $myVar ; then ... ; fi

because trueand falseare commands that return 0or 1respectively which is what ifexpects.

因为truefalse是返回01分别是if预期的命令。

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

请注意,这些值是“交换的”。之后的命令if必须0在成功时返回而0在大多数编程语言中表示“false”。

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 /

安全警告:这是有效的,因为 BASH 扩展了变量,然后尝试将结果作为命令执行!确保变量不能包含恶意代码,如rm -rf /

回答by Jens

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

请注意,该if $myVar; then ... ;fi构造存在您可能希望避免的安全问题

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 casesolution is also handled without forks.

您可能还想重新思考为什么if [ "$myvar" = "true" ]在您看来很尴尬。这是一个 shell 字符串比较,它击败了可能只是为了获得退出状态而对进程进行分叉的情况。fork 是一项繁重且昂贵的操作,而字符串比较则非常便宜。考虑几个 CPU 周期而不是几千个。我的case解决方案也是在没有分叉的情况下处理的。