Some resources to help me write good (or at least better) Bash scripts.
Please see the accompanying template.
- Template - Template for starting new scripts.
- Snippets - Reusable snippets.
- Scripts - A collection of full scripts.
- Use a recent version of Bash.
- MacOS (at the time of writing) uses an old version of Bash by default (3.2). Upgrade with e.g.
brew install bash
.
- MacOS (at the time of writing) uses an old version of Bash by default (3.2). Upgrade with e.g.
Tips for writing scripts, as opposed to interactive command line use.
- Use ShellCheck.
- Always prefer long form parameters (e.g.
--long-form
) over short form (e.g.-l
).- This makes scripts much more readable.
- Prefix variables with
local
inside functions.- Variables are globally scoped by default. This reduces the scope to just the function.
- Variable length arguments list
- Use an array:
some_cmd "${args[@]}"
- Use an array:
- Empty array expansion when using
nounset
- To support Bash <4.4:
${arr[@]+"${arr[@]}"}
- To support Bash <4.4: