A few other links along these lines that I’ve found useful over time:
Although I do wish OpenBSD’s base ksh had -o pipefail. Been working on a project in that for the past week.
I wish it had more ksh93 functionality as well; declare -A alone would be extremely nice.
‘set -euo pipefail’ is going in every single bash script i write from now on.
wonder how much of this applies to /bin/sh as opposed to /bin/bash. man builtin(1) always leaves me feeling deeply unsatisfied.
I’m all for it, but set -e can be painful when you expect things to fail and just have fallback positions.
That is say you have a grep for some text in a file and its not there. Thats not necessarily a “fail hard right now” condition.
Also most of this is common to not bash and old bourne will work with it. Not entirely sure about -o though, would have to login to an old sun box to find out.
I’m all for setting it and turning it off with set +x when needed, but it gets somewhat… tedious.
Beware the hidden perils of using set -e is all i’m saying.
I always use at least -o errexit and nounset, and can’t say I’ve run into unexpected pain. It does require turning potential failures into tests, a la
if/while [ "$(maybe_fail 2>&1)" ];
or is that what you were referring to?
Often if maybe_fail; then …; else …; fi is all you need when you do want to do something in the failure case, but ||: gives you +e behavior for a single command.
if maybe_fail; then …; else …; fi
In the case where you expect something to fail sometimes, you can || true as the article suggests, or ||: as I usually spell it. -e isn’t a panacea for not thinking about when your commands are going to fail, but it does reduce the frequency of putting terrible bugs into your scripts by not thinking about that, and opting out of -e with ||: is cheaper than opting out of +e with || exit 1.
|| exit 1
I worked on a project where the build consisted of a large number of bash and ant scripts. Bash scipts failed silently, and we ended up deploying a collection of old and new jar files. It took two days to understand what had happened.
I’ve also found using ‘trap’ to help make bash less painful.