SH

Shell Script Architecture

Modular and maintainable Shell/Bash script architecture patterns

Details

Language / Topic
shellShell/Bash
Category
Architecture

Rules

balanced
- Organize scripts into a `lib/` directory of sourced helper files and a thin entrypoint that calls `main "$@"` at the bottom.
- Use `source "$(dirname "$0")/lib/utils.sh"` with a path relative to the script location rather than relying on `$PWD`.
- Define one function per logical operation and keep each function under 30 lines — extract longer functions into named helpers.
- Use a consistent argument-parsing pattern with `getopts` or a `while [[ $# -gt 0 ]]` loop with `case` to handle flags and options uniformly.
- Emit structured output (JSON, key=value pairs) from library functions so callers can parse results without string scraping.
- Guard sourced library files with `[[ "${BASH_SOURCE[0]}" != "${0}" ]]` checks to allow them to be both sourced and directly tested.
- Use descriptive function names in verb-noun form (`parse_args`, `fetch_config`, `write_output`) to make the top-level `main()` self-documenting.