我怀疑这是故意的(而不仅仅是一个错误)。如果是这样,请指导我查看相关文档以获取理由。
~$ i=0; ((i++)) && echo true || echo false
false
~$ i=1; ((i++)) && echo true || echo false
true
两条线之间的唯一区别是i=0
vs i=1
。
答案1
这是因为i++
确实
后增量,如中所述man bash
。这意味着表达式的值为原来的的值i
,而不是增加的值。
ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and
declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no
check for overflow, though division by 0 is trapped and flagged as an error. The operators and their prece-
dence, associativity, and values are the same as in the C language. The following list of operators is
grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.
id++ id--
variable post-increment and post-decrement
以便:
i=0; ((i++)) && echo true || echo false
其行为类似于:
i=0; ((0)) && echo true || echo false
只不过它i
也增加了;然后:
i=1; ((i++)) && echo true || echo false
其行为类似于:
i=1; ((1)) && echo true || echo false
除了它i
也增加了。
如果该值非零,则该构造的返回值为(( ))
真 ( 0
),反之亦然。
您还可以测试后递增运算符如何工作:
$ i=0
$ echo $((i++))
0
$ echo $i
1
和预增量进行比较:
$ i=0
$ echo $((++i))
1
$ echo $i
1
答案2
]# i=0; ((i++)) && echo true || echo false
false
]# i=0; ((++i)) && echo true || echo false
true
an 的“返回”值((expression))
取决于前缀或后缀。然后逻辑是这样的:
((expression))
The expression is evaluated according to the rules described be low under ARITHMETIC EVALUATION.
If the value of the expression is non-zero,
the return status is 0;
otherwise the return status is 1.
这意味着它被转为正常值,而不是像返回值一样。