Hacker News new | ask | show | jobs
by j1elo 2169 days ago
I learnt the same trick some years ago, from an article called Shell Scripts Matter:

https://dev.to/thiht/shell-scripts-matter

So I took some of the advice and tips offered in there, and wrote a template file to be used as a baseline when writing scripts for any project that might need one:

https://github.com/j1elo/shell-snippets/blob/master/template...

Other resources that I link in the readme of that repo, because they were a great guide to write better and more robust scripts, are:

- Writing Robust Bash Shell Scripts: https://www.davidpashley.com/articles/writing-robust-shell-s...

- Common shell script mistakes: http://www.pixelbeat.org/programming/shell_script_mistakes.h...

- Bash Pitfalls: http://mywiki.wooledge.org/BashPitfalls

- The Bash Hackers Wiki: https://wiki.bash-hackers.org/

EDIT: -for anyone who would like to read some actual examples- I have to manage a bunch of scripts so actually a slightly more up to date version of the template is put into practice by means of a common bash.conf file that then gets sourced by all scripts: https://github.com/Kurento/adm-scripts/blob/master/bash.conf...

2 comments

Thank you for this really helpful comment. It's like an encyclopedia's worth of bash information in one go--much appreciated.
You're welcome! Shell scripting has a weird language, unsafe by default, and very prone to mistakes... but knowing it well pays off.

People say that for complex things it's better to write Python, but that doesn't fly in embedded or Docker environments. Python is not even present in the default Ubuntu Docker images. Also if all you want to do is really write glue code between CLI programs, shell scripting is the way to go.

Happy coding!

I'll second the thanks. Thanks!
A bash pitfall which I have experienced but didn’t see mentioned is the behavior of the `set -e` (errexit) option when using command substitution. If you expect failures within the command substitution to cause the script to exit, you’re gonna be confused.

https://twitter.com/hellsmaddy/status/1273744824835796993?s=...

Tl;dr use `shopt -s inherit_errexit`

Thanks. I wasn't aware of that option. I've added the following to my Bash-specific shell scripts:

    # Cause command substitution to inherit the value of the `errexit` option.
    # Introduced in Bash 4.4
    if [ "${BASH_VERSINFO[0]}" -gt 4 ] ||
      { [ "${BASH_VERSINFO[0]}" -eq 4 ] && [ "${BASH_VERSINFO[1]}" -ge 4 ]; }; then
        shopt -s inherit_errexit
    fi