Hacker News new | ask | show | jobs
by catern 3845 days ago
The only thing in this post that can be accurately called defensive is the use of "local" and "readonly". The rest is all just style preferences, which are rather subjective, and none of which are very appealing to me.

Three real defensive bash programming tips are:

- Quote all uses of variables

- set -o nounset

- set -o errexit

And many others can be found in and around http://mywiki.wooledge.org/BashFAQ

2 comments

While not as common as nounset and errexit, pipefail is a useful option as well (set -o pipefail).

Using pipefail, if any program in a pipeline fails (i.e. exit code != 0), then the exit code for the pipeline will be != 0.

E.g. pipefail can be useful to ensure `curl does-not-exist-aaaaaaa.com | wc -c` doesn't exit with exit code 0..!

You can set all three of them in a single line. Set up your Bash template with this today:

    set -o nounset -o pipefail -o errexit
I usually shorten this to:

    set -eu -o pipefail
I used to do that but the long versions are more understandable by other people who will look at the script.
Note that this can be shortened to "-e" and "-u":

    #!/...
    set -eu

    # ... Main part of your script ...
I'd used "set -e" and "set -u" before, but I had never seen it written as "-o nounset" and "-o errexit".

The latter makes it clearer exactly what features are being enabled, and it's a bit of a false economy to try and "shorten" the script like this.