Hacker News new | ask | show | jobs
by fsaintjacques 4172 days ago
Note to all, prepend all your bash script with

"set -o errexit -o nounset -o pipefail"

It'll save you headaches.

3 comments

Can you at least explain what this is doing, outside of saving me headaches?
-errexit: exit the script when a command fails -nounset: fail when referencing an unset variable -pipefail: fail when the any command in a pipeline fails, not just the last one

The last option is unfortunately harder to use, since some programs misbehave in pipelines.

set -o errexit (set -e): exit script when command fails

set -o nounset (set -u): exit script when it tries to use undeclared variables

set -o pipefail: returns error from pipe `|` if any of the commands in the pipe fail (normally just returns an error if the last fails)

I use the shebang "#!/bin/bash -e".

To get the same effect as the "set -o errexit -o nounset", I think you can use "#!/bin/bash -e -u". (There seems to be no option for pipefail.)

The "shebang" treats everything after the binary as a single argument. It only does one argument from the shebang and the file itself as the final argument. So it would run that kinda like

    bash '-e -u' $file
But you can do

    #!/bin/bash -eu
This breaks if your script is sourced by another shell. Best use 'set -eu' at the start instead.
Yep, my thought exactly. My standard bash header is

    #!/bin/bash
    set -eu
    IFS=$'\n\t'
(Wish there was a shorthand version of pipefail, then I'd always use that too.)
You can save a line by doing #!/bin/bash -eu
Which is no equivalent if the script is executed using "bash script.sh" ;).