Bash exit status of shorthand increment notation

前端 未结 2 1969
野趣味
野趣味 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
    
    0 讨论(0)
  • 2021-01-04 07:12

    The exit status of the (()) notation is zero if the arithmetic expression is nonzero, and vice versa.

    A=A+1
    

    You assign 1 to A, so the expression evaluates to 1, exit status zero.

    A++
    

    POST-increment operator. The expression evaluates to zero, exit status 1, and then A is incremented.

    0 讨论(0)
提交回复
热议问题