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.
((
to know if the command was working.. >> "If the result of the expression is 0, the exit status code returned will be 1 or “false”, while the exit status code returned by a non-zero value expression will be 0 or “true”." (via)declare -i a=0
thena+=1
.(( .. ))
to see if it worked, since a syntax error also makes it exit with status 1. (and not e.g. 2, like[
and[[
do)trap ... ERR
and this line provokes it. I have avoided this scenario, for now, by using pre-increment as my base value is 0 forvar
. But this solution is specific to my use case. Maybe I should search for a way to bypasstrap
for such/selected statements.