これは単なるバグではなく、意図的なものだと思います。もしそうなら、その根拠となる関連ドキュメントを教えてください。
~$ i=0; ((i++)) && echo true || echo false
false
~$ i=1; ((i++)) && echo true || echo false
true
2 つの行の唯一の違いは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
も増加します。
値がゼロ以外の場合、構造の戻り値は(( ))
truthy ( ) になり、その逆も同様です。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
の「戻り値」は、((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.
つまり、戻り値のようにではなく、通常の値に変換されます。