How can I get this script to error exit based on result of for loop?
Replace:
done
with:
done || exit 1
This will cause the code to exit if the for
loop exits with a non-zero exit code.
As a point of trivia, the 1
in exit 1
is not needed. A plain exit
command would exit with the exit status of the last executed command which would be false
(code=1) if the download fails. If the download succeeds, the exit code of the loop is the exit code of the echo
command. echo
normally exits with code=0, signally success. In that case, the ||
does not trigger and the exit
command is not executed.
Lastly, note that set -o errexit
can be full of surprises. For a discussion of its pros and cons, see Greg's FAQ #105.
Documentation
From man bash
:
for (( expr1 ; expr2 ; expr3 )) ; do list ; done
First, the arithmetic expression expr1 is evaluated according the rules described below under ARITHMETIC EVALUATION. The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, list is executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid. [Emphasis added]
If you prefer to stop the loop on the first failure, and also to avoid set -e
, you can do something like this:
for i in `seq 1 10`; do
run_command || exit 1;
done
If you have errexit
set, then the false
statement should cause the script to exit immediately. Same thing if the curl
command failed.
You're example script, as written, should exit after the first curl
command failure the first time it calls false
if errexit is set.
To see how it works (I use the shorthand -e
for to set errexit
:
$ ( set -e; false; echo still here )
$
$ ( set +e; false; echo still here )
still here
$
So if the curl
command executes more than once, this script doesn't have errexit
set.