Tuesday, April 30, 2024
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 2151  / 3 Years ago, fri, august 20, 2021, 6:54:02

Incrementing a variable var works in bash when enclosed in double parentheses like (( var++ )). But I have found that it fails if variable is set to 0 beforehand like var=0.


$ a=0
$ ((a++)) && echo "command succeeded" || echo "command failed"
command failed

$ a=1
$ ((a++)) && echo "command succeeded" || echo "command failed"
command succeeded


Can someone explain this behavior?


Environment:


I am using gnome-terminal on Ubuntu Desktop 18.04.5 LTS.


More From » command-line

 Answers
3

With credit from here: https://unix.stackexchange.com/questions/146773/why-bash-increment-n-0n-return-error


The return value of (( expression )) does not indicate an error status, but, from the bash manpage:



((expression))
The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is
non-zero, the return status is 0; otherwise the return status is 1.
This is exactly equivalent to let "expression".



In ((a++))you are doing a post increment. The value of a is 0 so 1 is returned, after that, it is incremented.


Compare


$ unset a
$ ((a++)) ; echo Exitcode: $? a: $a
Exitcode: 1 a: 1

versus


$ unset a
$ ((++a)) ; echo Exitcode: $? a: $a
Exitcode: 0 a: 1

A pre-increment, so a has become 1 and 0 is returned.


[#948] Saturday, August 21, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tubequ

Total Points: 11
Total Questions: 113
Total Answers: 115

Location: Equatorial Guinea
Member since Thu, Oct 7, 2021
3 Years ago
;