简体   繁体   中英

Bash post increment aborts script execution

Running with bash -e :

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM