brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ((i++)) stops a bash script under set -e when i is 0

Bash
~/tips/tip-bash-set-e-arithmetic-zero

set -e

Avoid a counter that silently ends your script on its first increment.

This one surprises people. A script with set -e and a counter dies on the very first ((i++)), without any error message.

(( )) returns exit status 1 when the expression evaluates to 0. i++ returns the old value, so when i was 0, the result is 0, the status is 1, and set -e ends the script:

set -e
i=0
((i++))
echo "never printed"

There are a few ways around it. Pick the one you find readable:

((++i))         # returns the new value, 1
i=$((i + 1))    # an assignment, always status 0
((i++)) || true # keep the form, ignore the status

I prefer i=$((i + 1)), because it cannot fail in any case and reads the same in every shell.

Do not assume ((++i)) is always safe either. If the counter starts at -1, the new value is 0 and you are back where you started. The same rule applies to any (( )) that can come out as zero, like (( count - expected )), which is often written exactly to test that. Only use (( )) as a statement when you are fine with it failing, or use it inside if, where set -e does not act.

Further reading: Bash manual: Shell Arithmetic, Bash manual: The Set Builtin

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link