Bash abbreviation exit status

I noticed a clear discrepancy in the return status of bash (( )) . Consider the following

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

However, using another known abbreviated increment, we get:

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

If the script has a built-in set -e , then the second entry will end the script, since the exit status ((A++)) returned non-zero. This question has been more or less considered in this related question . But this does not seem to explain the difference in output status for the two designations ((A=A+1)) and ((A++))

((A++)) seems to return 1 if and only if A is 0 . (Disclaimer: I did not do exhaustive tests. Tested in bash 4.1.2 and 4.2.25). Therefore, the last question boils down to the following:

Why is A=0; ((A++)) A=0; ((A++)) returns 1 ?

+7
bash
source share
2 answers

a++ is a post-increment: it increases after the instruction is evaluated. In contrast, ++a increases earlier. 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, and a is still zero, which gives a value of zero (and, therefore, a non-zero return status). Then, then a increases.

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

From man bash :

  id++ id-- variable post-increment and post-decrement ++id --id variable pre-increment and pre-decrement 
+4
source share

The output status of the notation (()) is zero if the arithmetic expression is non-zero, and vice versa.

 A=A+1 

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

 A++ 

POST-increment statement. The expression is zero, the state of output 1, and then A increases.

+2
source share

All Articles