bash中具有算术比较行为的if语句 [英] If statement with arithmetic comparison behaviour in bash

查看:65
本文介绍了bash中具有算术比较行为的if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习bash,但我注意到一些无法解释的怪异现象.在学校里,我了解到if语句将0评估​​为true,将1评估为false,因此可以将其与其他命令的状态代码一起使用.现在是我的问题:为什么会这样:

  echo $(((5> 2))#打印1echo $(((5< 2))#打印0如果((5> 2));然后回声是";否则回声不";fi #print是如果((5< 2));然后回声是";否则回声不";fi#打印否 

这似乎不合逻辑.bash如何知道我使用的是算术表达式而不是其他命令?

解决方案

$((...))是算术 expression ;它扩展为括号内表达式的值.由于它不是命令,因此它没有退出状态或返回值.布尔表达式为true时为1,为false时为0.

另一方面,

((...))是算术语句.它本身就是一条命令,其作用是将其主体作为算术表达式求值,然后查看结果值.如果值为true,则命令成功,退出状态为0.如果值为false,则命令失败,退出状态为1./p>

当学习 bash 来停止考虑 if 语句, while 循环等时的条件为真或不正确时,这是一个好主意.false,而是命令成功或失败.毕竟,shell语言不是为数据处理而设计的.它们是用于运行其他程序的粘合语言.

I'm learning bash and I noticed something weird I can't (yet) explain. At school I learned that an if statement evaluates 0 as true and 1 as false, so it can be used with the status code from an other command. Now is my question: Why does this happen:

echo $((5>2)) #prints 1
echo $((5<2)) #prints 0
if ((5>2)) ; then echo "yes" ; else echo "no" ; fi #prints yes
if ((5<2)) ; then echo "yes" ; else echo "no" ; fi #prints no

This doesn't seem logical. How does bash know i'm using an arithmetic expression and not another command?

解决方案

$((...)) is an arithmetic expression; it expands to the value of the expression inside the parentheses. Since it is not a command, it does not have an exit status or return value of its own. A boolean expression evaluates to 1 if it is true, 0 if it is false.

((...)), on the other hand, is an arithmetic statement. It is a command in its own right, which works be evaluating its body as an arithmetic expression, then looking at the resulting value. If the value is true, the command succeeds and has an exit status of 0. If the value is false, the command fails, and has an exit status of 1.

It's a good idea when learning bash to stop thinking of the conditions in if statements, while loops, etc. as being true or false, but rather if the commands succeed or fail. After all, shell languages are not designed for data processing; they are a glue language for running other programs.

这篇关于bash中具有算术比较行为的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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