3 ms·
Safer bash scripts with 'set -euxo pipefail' (2015)
- LinuxBender 8y agoAll good points. I would also pass all shell scripts through shellcheck [1] as well. There is a command line version available for most Linux distros. You can add comments to your script to ignore specific checks. [1] - https://www.shellcheck.net/ https://www.shellcheck.net/
- baylisscg 8y agoHilariously I was having to write init.d scripts for a crusty version of CentOS yesterday and used `set -e` instinctively. Died inexplicably importing `/etc/init.d/functions` until I noticed a comment explicitly saying to _not_ set that.
- xelxebar 8y agoSince we're using `-o` already, we might like the equivalent "longoptions" form: ``` set -o errexit -o nounset -o noclobber -o pipefail ``` But `pipefail` isn't part of POSIX and will fail in dash, tcsh, and friends, so it's arguably better to go ahead and use your shell-specific builtin whenever possible---`shopt` for bash, `setopt` for zsh, etc. ``` shopt -s -o errexit nounset noclobber pipefail ``` For that matter, if we're using shell-specific features, we might as well use the appropriate bang pattern: ``` #!/usr/bin/env bash ``` or similar. It's also really nice that Shellcheck differentiates between shells based on bang patterns and changes it's behavior accordingly. Also, I can't help but mention the bash unit testing framework, BATS!