我懷疑這是故意的(而不僅僅是一個錯誤)。如果是這樣,請指導我查看相關文件以獲取理由。
~$ 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.
這意味著它被轉為正常值,而不是像返回值一樣。