How to Write Shell Scripts
How to Write Shell Scripts and don’t go ballistic in the process.
- Lint your scripts with shellcheck. This is the most important rule. Shell programming is ridden with foot guns. Linter catches most of them.
- 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. - If you feel like your script requires some Bash features (in example arrays) - rewrite it in real programming language.
- It’s longer than one page of code? Rewrite it in real programming language!
- It’s more complex than gluing a few commands together or piping data through some programs? See above.
set -euf
is a sane default.- Use a code formatting tool.
- It’s used to build stuff? Use make or other build system.
- 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.