速记增量表示法的Bash退出状态 [英] Bash exit status of shorthand increment notation

查看:53
本文介绍了速记增量表示法的Bash退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到bash的(())表示法的返回状态存在明显不一致.
考虑以下

I noticed an apparent inconsistency in the return status of bash's (( )) notation.
Consider the following

$> A=0
$> ((A=A+1))
$> echo $? $A
0 1

但是使用其他众所周知的速记增量表示法会得出:

However using the other well known shorthand increment notation yields:

$> A=0
$> ((A++))
$> echo $? $A
1 1

如果脚本中具有内置的 set -e ,则第二种表示法将导致脚本退出,因为返回了((A ++))的退出状态非零.

If one has the builtin set -e in the script the second notation will cause the script to exit, since the exit status of the ((A++)) returned non-zero. This question was more or less addressed in this related question. But it does not seem to explain the difference in exit status for the two notations ((A=A+1)) and ((A++))

(((A ++))"似乎返回 1 .(免责声明:我尚未进行详尽的测试.已在bash 4.1.2和4.2.25中进行了测试).因此,最后一个问题归结为:

((A++)) seems to return 1 if and only if A equals 0. (Disclaimer: I have not done exhaustive tests. Tested in bash 4.1.2 and 4.2.25). So the final question boils down to:

为什么 A = 0;(((A ++)) return 1 ?

Why does A=0; ((A++)) return 1?

推荐答案

a ++ 是后递增的:它在对语句求值后递增.相比之下, ++ a 之前增加.因此:

a++ is post-increment: it increments after the statement is evaluated. By contrast, ++a increments before. Thus:

$ a=0 ; ((a++)) ; echo $a $?
1 1
$ a=0 ; ((++a)) ; echo $a $?
1 0

在第一种情况下,((a ++))首先计算算术表达式,而 a 仍为零,得出零值(因此,a为零).非零返回状态).然后,随后 a 递增.

In the first case, ((a++)), the arithmetic expression is evaluated first, while a is still zero, yielding a value of zero (and hence a nonzero return status). Then, afterward, a is incremented.

在第二种情况下,((++ a)) a 递增为1,然后是((...))被评估.由于在计算算术表达式时 a 不为零,因此返回状态为零.

In second case, ((++a)), a is incremented to 1 and then ((...)) is evaluated. Since a is nonzero when the arithmetic expression is evaluated, the return status is zero.

来自 man bash :

   id++ id--
          variable post-increment and post-decrement
   ++id --id
          variable pre-increment and pre-decrement

这篇关于速记增量表示法的Bash退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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