Bash exit status of shorthand increment notation

前端 未结 2 1970
野趣味
野趣味 2021-01-04 06:46

I noticed an apparent inconsistency in the return status of bash\'s (( )) notation.
Consider the following

$> A=0
$> ((A=A+1)         


        
2条回答
  •  春和景丽
    2021-01-04 07:02

    a++ is post-increment: it increments after the statement is evaluated. By contrast, ++a increments before. Thus:

    $ a=0 ; ((a++)) ; echo $a $?
    1 1
    $ a=0 ; ((++a)) ; echo $a $?
    1 0
    

    In the first case, ((a++)), the arithmetic expression is evaluated first, while a is still zero, yielding a value of zero (and hence a nonzero return status). Then, afterward, a is incremented.

    In second case, ((++a)), a is incremented to 1 and then ((...)) is evaluated. Since a is nonzero when the arithmetic expression is evaluated, the return status is zero.

    From man bash:

       id++ id--
              variable post-increment and post-decrement
       ++id --id
              variable pre-increment and pre-decrement
    

提交回复
热议问题