logo TeddyDD

How to Write Shell Scripts

How to Write Shell Scripts and don’t go ballistic in the process.

  1. Lint your scripts with shellcheck. This is the most important rule. Shell programming is ridden with foot guns. Linter catches most of them.
  2. Avoid Bash. Use POSIX /bin/sh. This rule is not about portability. I don’t give two fucks about systems other than Linux and eventually macOS and *BSD. It’s about Bash pretending to be decent programming language It does it by adding features with the most obnoxious syntax possible. Neither shell is good programming language but at least POSIX sh limitations will hit you before your script becomes an unmaintainable mess.
  3. If you feel like your script requires some Bash features (in example arrays) - rewrite it in real programming language.
  4. It’s longer than one page of code? Rewrite it in real programming language!
  5. It’s more complex than gluing a few commands together or piping data through some programs? See above.
  6. set -euf is a sane default.
  7. Use a code formatting tool.
  8. It’s used to build stuff? Use make or other build system.
  9. Feel free to write personal scripts in your interactive shell. I use Fish and I have a ton of scripts written in it. I don’t plan to share those scripts. Worst case scenario - I’ll just rewrite them.
Published: