0

Running with bash -e:

round=0
((round++))
echo "Done"

Will not show Done. Why? How can I use post-increment when -e is set?

volingas
  • 1,023
  • 9
  • 21
  • I believe `((expr))` is a Bash-ism. You need to use Bash as the interpreter. Add the shebang. See [What is the preferred Bash shebang?](https://stackoverflow.com/q/10376206/608639) Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Dec 06 '19 at 07:32
  • This is one of many ways that `set -e` can have weird effects. See [BashFAQ #105: Why doesn't `set -e` (or `set -o errexit`, or `trap ERR`) do what I expected?](https://mywiki.wooledge.org/BashFAQ/105) – Gordon Davisson Dec 06 '19 at 07:53

1 Answers1

3

Please take a look of some examples:

round=0
((round++))
echo $?

round=1
((round-1))
echo $?

((0))
echo $?

In all cases $? returns 1.

Bash manpage states:

((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".

If the -e option is set, then the script exits because:

-e
Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status. ...

You can avoid the termination by assigning a variable to the result of arithmetic evaluation:

set -e
round=0
dummy=$((round++))
echo "Done"

Hope this helps.

tshiono
  • 21,248
  • 2
  • 14
  • 22