如何在bash的if块评估一个布尔变量? [英] How to evaluate a boolean variable in an if block in bash?

查看:88
本文介绍了如何在bash的if块评估一个布尔变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了以下变量:

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

以上code的工作,但如果我尝试设置

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

myVar=false

它依然会输出真。
可能是什么问题?

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

编辑:我知道我可以做形式的东西。

edit: I know I can do something of the form

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

但它是有点尴尬。

but it is kinda awkward.

感谢

推荐答案

庆典不知道布尔变量,也不测试(这是当你使用什么被调用 [)。

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

一个解决方案是:

if $myVar ; then ... ; fi

由于真正是返回的命令 0 1 分别是什么如果预计。

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

请注意,该值是交换。在的命令,如果必须返回 0 上的成功,同时 0 意味着大多数编程语言假。

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

这篇关于如何在bash的if块评估一个布尔变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆