The `die()` trick is good, but bash has an annoying quirk: if you try to `exit` while you're inside a subshell, then the subshell exits but the rest of the script continues. Example: #!/bin/bash die() { echo "$1" >&2; exit 1; } cat myfile | while read line; do if [[ "$line" =~ "information" ]]; then die "Found match" fi done echo "I don't want this line" ..."I don't want this line" will be printed. You can often avoi…
Just adding `set -e` also exits the script when a subshell exits with non-zero error code. I'm not sure why I would leave `set -e` out in any shell script.
An arithmetic expression that evaluates to zero will cause the script to exit. e.g this will exit:
set -e
i=0
(( i++ )) # exits
Calling a function from a conditional prevents `set -e` from exiting. The following prints "hello\nworld\n": set -e
main() {
false # does not return nor exit
echo hello
}
if main; then echo world; fi
Practically speaking this means you need to explicitly check the return value of every command you run that you care about and guard against `set -e` in places you don't want the script to exit. So the value of `set -e` is limited.