top | item 26320300

(no title)

pmahoney | 5 years ago

I stopped using `set -e`. It is disabled if the function you're running is part of an `if` statement, for example:

    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.

discuss

order

ktpsns|5 years ago

That's the same approach I am using in all my scripts. You can even combine that with `set -e` and run some

    commandThatMayFail || true
in order to continue the script if some optional step fails.

Bonus note: The notation "do something else die 'with message'" stems from Perl, AFAIK. See for instance https://perldoc.perl.org/Carp