我怀疑这是故意的(而不仅仅是一个错误)。如果是这样,请指导我查看相关文档以获取理由。
~$ i=0; ((i++)) && echo true || echo false
false
~$ i=1; ((i++)) && echo true || echo false
true
Run Code Online (Sandbox Code Playgroud)
这两行之间的唯一区别是i=0
vs i=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
Run Code Online (Sandbox Code Playgroud)
以便:
i=0; ((i++)) && echo true || echo false
Run Code Online (Sandbox Code Playgroud)
行为如下:
i=0; ((0)) && echo true || echo false
Run Code Online (Sandbox Code Playgroud)
除了它i
也增加了;然后:
i=1; ((i++)) && echo true || echo false
Run Code Online (Sandbox Code Playgroud)
行为如下:
i=1; ((1)) && echo true || echo false
Run Code Online (Sandbox Code Playgroud)
除了它i
也增加了。
如果值非零,则(( ))
构造的返回值为真 ( 0
),反之亦然。
您还可以测试后增量运算符的工作方式:
$ i=0
$ echo $((i++))
0
$ echo $i
1
Run Code Online (Sandbox Code Playgroud)
并预先递增进行比较:
$ i=0
$ echo $((++i))
1
$ echo $i
1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
204 次 |
最近记录: |