16 ms·
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 rath
by catern 11y 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 http://mywiki.wooledge.org/BashFAQ
- krallin 11y agoWhile 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..!
- michaelhoffman 11y agoYou 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
- vog 11y agoI usually shorten this to: set -eu -o pipefail
- michaelhoffman 11y agoI used to do that but the long versions are more understandable by other people who will look at the script.
- vog 11y agoNote that this can be shortened to "-e" and "-u": #!/... set -eu # ... Main part of your script ...
- wyldfire 11y agoI'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.