Shell exit silently at arithmetic expression in for loop
A simple example should explain why:
$ ((success++))
$ echo $?
1
The reason is that any arithmetic operation which produces a numeric value of zero returns 1. I don't know what to say - Bash has gotchas enough for the whole world.
It is the consequence of having -e
set.
Any command with an exit code of 1 (not zero) will trigger an exit.
This script works fine:
#!/bin/bash
(( success++))
echo "Still going 1 $success"
This doesn't
#!/bin/bash
set -e
(( success++))
echo "Still going 1 $success"
Solutions
The simplest is to remove the set -e
line.
If that is not an option, Use this:
(( ++success ))
Other alternatives:
#!/bin/bash
set -e
success=0
success=$(( success+1 ))
echo "still going 1 $success"
success=0
(( success=success+1 ))
echo "still going 2 $success"
success=0
(( success+=1 ))
echo "still going 3 $success"
success=0
(( ++success ))
echo "still going 4 $success"
success=0
(( success++ ))
echo "still going 5 $success"
Only the option number 5 will have an exit code of 1.
Other (more complex solutions for any value of variable a
).
The first one uses the (POSIX) colon (:
) builtin to make it POSIX compatible.
: $(( a+=1 )) ; echo "6 $a $?" ## Valid Posix
(( a++ )) || true ; echo "7 $a $?"
(( a++ )) || : ; echo "8 $a $?"
(( a++ , 1 )) ; echo "9 $a $?"
(( a++ | 1 )) ; echo "10 $a $?"