❌ Checking for failure/success, even up the chain prevents 'set -e' from triggering.❌
To show in an example, how set -e
is prevented from triggering if up the chain we have a success or error branch.
Let's say we have the following code.
#!/usr/bin/env bash
set -e
echo_with_pid(){
echo "[\$\$=$$/$BASHPID] $*"
}
foo2() {
echo_with_pid "foo2-enter"
i_dont_exist
echo_with_pid "foo2-exit"
}
foo1() {
echo_with_pid "foo1-enter"
foo2
echo_with_pid "foo1-exit"
}
main() {
echo_with_pid "START"
foo1
echo_with_pid "DONE"
}
# If we just call main, `set -e` works as one would expect
main
Aborts execution and giving us the following output:
[$$=37290/37290] START
[$$=37290/37290] foo1-enter
[$$=37290/37290] foo2-enter
/tmp/scratch.sh: line 11: i_dont_exist: command not found
BUT, if we were to check the return code of main
, the behavior becomes quite un-intuitive.
# If we run with having just a success branch (no failure branch), the not-found command get's masked.
if main; then
echo "Main succeeded"
fi
❯/tmp/scratch.sh
[$$=38049/38049] START
[$$=38049/38049] foo1-enter
[$$=38049/38049] foo2-enter
/tmp/scratch.sh: line 11: i_dont_exist: command not found
[$$=38049/38049] foo2-exit
[$$=38049/38049] foo1-exit
[$$=38049/38049] DONE
Main succeeded
command_not_found_handle does not have this issue and is able to catch
Backlinks