Skip to content

Instantly share code, notes, and snippets.

@aprell
Created June 5, 2022 14:43
Show Gist options
  • Save aprell/64959fc612ed63982f086c3165a6182d to your computer and use it in GitHub Desktop.
Save aprell/64959fc612ed63982f086c3165a6182d to your computer and use it in GitHub Desktop.
Be wary of arithmetic expressions when using `set -e`
#!/usr/bin/env bash
set -e
i=0
while [ $i -lt 3 ]; do
r=$((RANDOM % 10))
if [ $r -lt 3 ]; then
((i++))
fi
done
echo "Done: i = $i"
@aprell
Copy link
Author

aprell commented Jun 5, 2022

$ ./gotcha.sh
$ # Nothing

Use either ((++i)) or i=$((i + 1)) in this case. The reason:

$ i=0; ((i++)); echo $?
1
$ i=0; ((++i)); echo $?
0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment