(no title)
pmahoney | 5 years ago
thingThatCanFail() {
echo "step one succeeded"
echo "step two failed"
false
echo "step three was run too"
}
if ! thingThatCanFail; then
echo "thingThatCanFail failed!"
fi
With or without `set -e`, step three is run, and the function returns success, even though you might expect the failure of step two to prevent step three from running.If "thingThatCanFail" is called _outside_ of an if statement, then `set -e` causes different behavior (i.e. step three _is_ skipped).
I instead use lots of chaining with && (as in the article), or explicit checks after each command. I have two utility functions I define in nearly every script:
warn() { >&2 printf "%s\\n" "$*"; }
abort() { warn "$@"; exit 1; }
Then I do lots of: stepOne || abort "step one failed"
stepTwo || abort "step two failed"
...
It can get a little verbose, but much better than trying to reason about `set -e` in my opinion.
ktpsns|5 years ago
Bonus note: The notation "do something else die 'with message'" stems from Perl, AFAIK. See for instance https://perldoc.perl.org/Carp