Shell Scripting
Overview
Write scripts that are safe by default, easy to read, and predictable across repeated runs.
For new scripts, start from assets/script-template.sh.
Workflow
- Confirm scope and runtime assumptions (bash version, OS expectations, required tools).
- Start from
assets/script-template.shand adapt it. - Keep parsing explicit (
-h,--help,--) and fail on unknown flags. - Keep operations idempotent where practical (safe re-runs, no destructive defaults).
- Validate with:
bash -n <script>- a small functional smoke run with safe inputs
Output Style
Use structured output helpers:
log_error: red + bold prefix (ERROR:), stderrlog_warn: yellow, stderrlog_note: dim informational notelog_success: green success output
Use ANSI styling only when interactive:
- enable color when
-t 1or-t 2 - disable color when
TERM=dumborNO_COLORis set
Keep usage output readable:
- bold section headers (
Usage,Options,Examples) - highlight command examples in cyan
- keep notes concise and actionable
Core Practices
- Use
#!/usr/bin/env bashandset -euo pipefail. - Quote variable expansions unless intentionally using word splitting.
- Use
localfor function-scoped variables. - Prefer
printfoverechofor structured output. - Validate required commands early (for example with
command -vchecks). - Use
mktempfor temporary files/dirs and cleanup withtrap. - Avoid destructive actions by default; require explicit opt-in for risky actions.
- Keep scripts composable and testable with small functions.
Resources
assets/script-template.sh: baseline script template with rich usage/log output.references/best-practices.md: expanded checklist and patterns.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.