4 ms·
There is a gotcha here if you use: set -o errexit Because *any bash arithmetic expression that evaluates to zero returns the exit code of 1*. So this works
by cmckn 4y ago
There is a gotcha here if you use:
set -o errexit
Because *any bash arithmetic expression that evaluates to zero returns the exit code of 1*.
So this works:
#!/usr/bin/env bash
set -o errexit
i=0
((++i))
echo $i # 1 will be printed to stdout
But this doesn't:
#!/usr/bin/env bash
set -o errexit
i=0
((i++)) # terminates here with $? of 1
echo $i
The relevant doc is for `let`:
let arg [arg ...]
Each arg is an arithmetic expression to be evaluated (see
ARITHMETIC EVALUATION above). If the last arg evaluates
to 0, let returns 1; 0 is returned otherwise.
https://www.gnu.org/software/bash/manual/bash.html#index-let https://www.gnu.org/software/bash/manual/bash.html#index-let
- chubot 4y agoYeah it's best to just use POSIX shell arithmetic, and not be clever, and not the other 2 ways bash has to do it! THat is: i=$((i + 1)) The (( )) construct, without the $, is different, and it's also not POSIX. It has the gotchas around the exit code, which a plain assignment doesn't have.