This is the baseline Bash shell script template I use for new projects, from the simple to the complex.
A huge hat tip to the original foundation I used for this on betterdev.blog (raw source). Another blog resource I referenced and learned from was on betterprogramming.pub.
This has been tested and used almost exclusively on macOS, but I don't think there is anything specific to macOS built into the script, or at least not to the detriment of any other platforms.
Copy the shell-script-template.sh
file into your new script:
cp shell-script-template.sh my-new-script.sh
Customize the script for your solution.
Hint: Search for "TODO", the areas that require focus are tagged with TODOs.
The highest priority changes are to modify the usage
function to print out a summary about the script and update/remove the options
for your script, update the argument parsing that corresponds to the usage
information, then implement the body of the script.
There are some "nice to have" changes like adding parameter validation, additional utility functions, etc.
You will notice that getopt
is not used, this is because of an incompatibility with macOS.
Colorized output uses 3 and 4-bit colors (more info on Wikipedia) and has only really been tested on very dark backgrounds. Where multiple variants of a color exist, I typically used the bright variant. There is also some great discussion on the topic on StackExchange.
I highly recommend the ShellCheck LINTing tool, it provides a lot of really useful feedback regarding problematic or error-prone aspects of a shell script.
Unit testing for shell scripts is a wide-ranging topic with no shortage of available libraries. I have only just begun this research, but so far this summary on Medium from wemake-services seems to have a nice concise outline of pros/cons of some common libraries. This dodie/testing-in-bash repo also contains a useful overview of feature support for popular libraries.
I am inclined to use bats-core
, but I suspect there are several good choices.