top | item 18495376

Safer bash scripts with 'set -euxo pipefail' (2015)

19 points| devy | 7 years ago |vaneyckt.io | reply

3 comments

order
[+] LinuxBender|7 years ago|reply
All 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/

[+] xelxebar|7 years ago|reply
Since 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!

[+] baylisscg|7 years ago|reply
Hilariously 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.