State: set -euxo pipefail ?
“I hope to convince you that it’s a really good idea to add
set -euxo pipefail
to the beginning of all your future bash scripts.” - Quote from a random article I googled.
Erm, no. set -euxo pipefail
may be useful for very small projects, but
blindly adding these options may actually break your scripts. This is a very
abridged table of the options in question (the
bash documentation
is much better).
Option | Short Description |
---|---|
-e |
Exit immediately if a command exits with a non-zero status. |
-o pipefail |
Set return code to the status of the last process in a pipe. |
-u |
Bail if an undefined variable gets accessed. |
-x |
Trace almost every command. |
-e
This is very limiting, as you can not use values other than zero as
Function Return Values.
You can also not postpone checks of the return value.
The alternative is to affix || exit 1
to the function calls, you don’t
expect to fail. I think it’s worth the effort.
-o pipefail
I have no problems and indeed use pipefail as the default setting in my scripts.
-u
-u
is pretty much obsoleted by ShellCheck
which will warn you about the use of an uninitialized variable. This frees you
from some tedious coding practices needed to support -u
.
If you chose to use -u
you’d have to adapt naming your parameters
to declare optional parameters as local optional_parameter="${2:-}
.
Testing for possibly uninitialized environment variables needs to be done
either likewise or with a [[ ${ENV_VAR+x} ]]
test, that checks for set/unset
status.
-x
As soon as your scripts grow to a few hundred lines, you will turn this off as a default!
Note
shopt -s extglob
expands the wildcards available to shell scripts.I think it is very useful forcase
statements and think its usefully set as a script default.
Keep default shell state
I think you are shooting yourself in the foot, if you aren’t keeping the shell state as close to the default as possible for compatibility. Assume that your function is in default state, and if you need to change it, reset to default before calling another function or leaving the functions.
pipefail
and extglob
appear to be harmless changes.