为什么$((真== FALSE))计算为1在bash? [英] Why does $((true == false)) evaluate to 1 in bash?

查看:101
本文介绍了为什么$((真== FALSE))计算为1在bash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么bash中有下列行为?

回声$((真== FALSE))
1

我还以为这将打印 0 ,但它打印 1

这进一步复杂化由下面的事实:

 >回声$((真))
0
>回声$((假))
0
>回声$((真== true)而)
1
>回声$((假== FALSE))
1


解决方案

所有海报谈论0为真,1为假错过了点。在这种情况下,1是真实的,0是因为由 $算术评估上下文在通常布尔感假(())

$里面的 == 操作(())是不是在Bash的返回状态的平等,它进行利用给定的文字,其中假和真被视为可变,但尚未被束缚,这两者都是除preTED为0,因为它们没有尚未分配值数值等于:

  $回声$((真))
0
$回声$((假))
0

如果要比较你想要的东西喜欢的真假返回状态:

 
TRUE = $?

FALSE = $?
如果(($ TRUE == $ FALSE));然后回显TRUE;否则回声FALSE;科幻

不过,我不知道你为什么会想这样做。

编辑:修正了关于真与假是PTED为字符串间$ P $原来答案的一部分。他们不是。他们被视为变量,但没有任何价值势必他们没有。

Why does bash have the following behavior?

echo $((true == false))
1

I would have thought that this would print 0, but it prints 1.

This is further complicated by the following facts:

> echo $((true))
0
> echo $((false))
0
> echo $((true == true))
1
> echo $((false == false))
1

解决方案

All the posters talking about 0 being true and 1 being false have missed the point. In this case, 1 is true and 0 is false in the usual boolean sense because of the arithmetic evaluation context caused by $(()).

The == operation inside of $(()) is not equality of return statuses in Bash, it performs numeric equality using the literals given where "false" and "true" are treated as variable, but have not yet been bound, which both are interpreted as 0 since they have no value yet assigned:

$ echo $((true))
0
$ echo $((false))
0

If you want to compare the return status of true and false you want something like:

true
TRUE=$?
false
FALSE=$?
if (( $TRUE == $FALSE )); then echo TRUE; else echo FALSE; fi

But, I'm not sure why you would want to do this.

EDIT: Corrected the part in the original answer about "true" and "false" being interpreted as strings. They are not. They are treated as variables, but have no value bound to them yet.

这篇关于为什么$((真== FALSE))计算为1在bash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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