Bash 脚本 - if 块中的布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18005640/
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-18 06:06:26  来源:igfitidea点击:

Bash scripting - Boolean in if block?

linuxbashunixboolean

提问by Steam

I tried the code in this SO post - How to evaluate a boolean variable in an if block in bash?and it does not work. It looks like there are no booleans in BASH. Is there a flawless workaround which lets me set and check booleans in BASH ?

我尝试了这篇 SO 帖子中的代码 -如何在 bash 的 if 块中评估布尔变量?它不起作用。看起来 BASH 中没有布尔值。是否有完美的解决方法可以让我在 BASH 中设置和检查布尔值?

My code -

我的代码 -

#!/bin/bash
flag=true
if [ $flag ]
echo 'True'
#flag=false
#echo 'Now changed to false' 
fi

Even if flag=false in line 2, output is still True. Why ?

即使第 2 行中的 flag=false,输出仍然为 True。为什么 ?

回答by Cristian Meneses

Try without square brackets, like this

尝试不使用方括号,像这样

#!/bin/bash
flag=true
if $flag ; then
   echo 'True'
   #flag=false
   #echo 'Now changed to false' 
fi

回答by Omeganon

It evaluates to true because of this part of 'man test' -

由于“人测试”的这一部分,它评估为真 -

 [ expression ]
         string        True if string is not the null string.

You need to use something like -

你需要使用类似的东西 -

#!/bin/bash
flag=1
if [ ${flag} -eq 1 ]
then
    echo 'True'
    #flag=0
    #echo 'Now changed to false' 
fi