Bash変数の増加、一貫性のない動作

Bash変数の増加、一貫性のない動作

私はこれがバグではなく意図的なものだと思います。その場合は、根拠に関する関連文書をご案内ください。

~$ i=0; ((i++)) && echo true || echo false
false
~$ i=1; ((i++)) && echo true || echo false
true

2行の唯一の違いはi=0vs。i=1

ベストアンサー1

i++本当にそうだからです。ポスト増分で説明されているようにman bash。これは、式が次のように評価されることを意味します。オリジナルvalue 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でない場合、この構成の戻り値は(( ))true(0)であり、その逆も同様です。

事後増加演算子がどのように機能するかをテストすることもできます。

$ i=0
$ echo $((i++))
0
$ echo $i
1

事前増分と比較:

$ i=0
$ echo $((++i))
1
$ echo $i
1

おすすめ記事