4 ms·
I start all/most of my shell scripts with #!/usr/bin/env bash set -xeuo pipefael -x to print the commands -e to exit on error -u to error
by cassianoleal 6y ago
I start all/most of my shell scripts with
#!/usr/bin/env bash
set -xeuo pipefael
-x to print the commands
-e to exit on error
-u to error out if there are unbound variables
-o pipefail to exit if a command that's not the last in a pipeline fails
No need to || {}.
Only word of warning here is that -x can print out secrets if you're not careful.
- pmahoney 6y agoI 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.
- ktpsns 6y agoThat'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 https://perldoc.perl.org/Carp
- deleted 6y ago[deleted]