[H1][BASH-SCRIPT-GENERATOR]
Dictum: Functional patterns and strict mode produce maintainable shell automation.
Generate bash scripts with immutable locals, dispatch tables, pure functions, and zero mutable state.
Tasks:
- Clarify requirements — Purpose, I/O, shell type, args, error strategy, performance constraints.
- Read bash-scripting-guide.md — Strict mode, parameter expansion, arrays, bash 5.2/5.3 features.
- Read script-patterns.md — Argument parsing, logging, parallel processing, retry, signals.
- Read text-processing-guide.md — rg/awk/sd selection, pipeline patterns, performance.
- Structure script — Shebang + strict mode + readonly constants + trap + main.
- Implement — Core functions, business logic, main entry point.
- Validate —
bash -n script.sh, ShellCheck 0.11.0+, re-validate until clean.
[1][REQUIREMENTS]
Dictum: Ambiguity resolution prevents rework.
Clarify before generating:
| [INDEX] |
[AMBIGUITY] |
[QUESTION] |
| [1] |
Data format |
Input format? (nginx combined, JSON, CSV, custom) |
| [2] |
Large files |
Files >100MB? Optimize for memory/performance? |
| [3] |
Error handling |
Fail fast, continue with warnings, or retry? |
| [4] |
Portability |
POSIX sh portability or bash 5.2+/5.3? |
| [5] |
Output format |
Human-readable, JSON, or CSV? |
Guidance:
- Architecture First: Explain design, tool selection rationale, key tradeoffs before writing code.
- Data Format Routing: JSON?
jq. YAML? yq eval. CSV/TSV? miller (mlr). Interactive exploration? jnv.
- Template: Reference
assets/templates/standard-template.sh for production boilerplate.
[2][STRICT_MODE]
Dictum: Strict mode prevents silent failures.
#!/usr/bin/env bash
set -Eeuo pipefail # -E = errtrace (ERR trap inherits into functions/subshells)
shopt -s inherit_errexit # Command substitutions inherit errexit
IFS=$'\n\t'
Guidance:
- Scope: Every generated script includes this block. No exceptions.
- Disable: Temporarily suppress —
output=$(cmd 2>&1) || handle_error "${output}".
[3][FUNCTIONAL_STYLE]
Dictum: Immutability and dispatch tables eliminate mutable state.
| [INDEX] |
[RULE] |
[PATTERN] |
| [1] |
Immutable locals |
local -r for all non-mutating variables inside functions |
| [2] |
Immutable globals |
readonly for all module-level constants |
| [3] |
Pure functions |
Input via args, output via stdout or nameref (local -n), no global state |
| [4] |
Dispatch tables |
declare -Ar for O(1) routing; case/esac only for pattern matching |
| [5] |
Higher-order |
Pass function names as args; local -n nameref for array parameters |
| [6] |
Inline trivials |
Single-use < 3 lines: inline at call site |
| [7] |
Brace grouping |
{ cmd1; cmd2; } > file over ( ... ) (no subshell) |
| [8] |
No mutable counters |
${#arr[@]}, rg -c, or awk pipelines for counting |
| [9] |
mapfile/readarray |
Over while read loops for array population (3-5x faster) |
| [10] |
printf everywhere |
Over echo (handles escapes, format strings, no ambiguity) |
| [11] |
$(<file) |
Over $(cat file) (no fork) |
| [12] |
printf -v |
printf -v var '%(%F %T)T' -1 over $(date ...) (no subshell) |
| [13] |
Here-strings |
<<< over echo x | cmd pipelines |
| [14] |
BASH_REMATCH |
[[ str =~ regex ]] + ${BASH_REMATCH[N]} over rg -oP / sd |
| [15] |
Assoc set |
declare -Ar SET=([k]=1) + [[ -v SET[key] ]] for O(1) membership |
| [16] |
IFS splitting |
IFS=, read -ra parts <<< "$csv" over cut / awk -F, for simple delim |
Best-Practices:
- Nameref Constraint: Array variables cannot be namerefs, but namerefs can reference arrays.
- Dispatch Declaration:
declare -Ar assigns on declaration line; separate assignment fails for readonly.
- Structured Checks:
declare -Ar CHECKS=([name]="pattern\|msg\|level") + IFS=\| read -r for data-driven validation.
[4][QUALITY_GATE]
Dictum: Checklists prevent omissions.
[VERIFY] Generation:
[REFERENCE]: docs/bash-scripting-guide.md — Language features, parameter expansion, arrays.
[REFERENCE]: docs/script-patterns.md — Argument parsing, logging, parallel, retry.
[REFERENCE]: docs/text-processing-guide.md — Tool selection, rg/awk/sd, performance.
1---2name: bash-script-generator-23description: Generates production-ready bash 5.2+/5.3 scripts with strict mode, immutable locals, dispatch tables, and functional patterns. Use when creating new .sh scripts, CLI tools, cron jobs, deployment automation, text processing workflows, or log analyzers.4---5
6# [H1][BASH-SCRIPT-GENERATOR]
7>**Dictum:** *Functional patterns and strict mode produce maintainable shell automation.*
8
9<br>
10
11Generate bash scripts with immutable locals, dispatch tables, pure functions, and zero mutable state.
12
13**Tasks:**
141. Clarify requirements — Purpose, I/O, shell type, args, error strategy, performance constraints.
152. Read [bash-scripting-guide.md](./docs/bash-scripting-guide.md) — Strict mode, parameter expansion, arrays, bash 5.2/5.3 features.
163. Read [script-patterns.md](./docs/script-patterns.md) — Argument parsing, logging, parallel processing, retry, signals.
174. Read [text-processing-guide.md](./docs/text-processing-guide.md) — rg/awk/sd selection, pipeline patterns, performance.
185. Structure script — Shebang + strict mode + readonly constants + trap + main.
196. Implement — Core functions, business logic, main entry point.
207. Validate — `bash -n script.sh`, ShellCheck 0.11.0+, re-validate until clean.
21
22---
23## [1][REQUIREMENTS]
24>**Dictum:** *Ambiguity resolution prevents rework.*
25
26<br>
27
28Clarify before generating:
29
30| [INDEX] | [AMBIGUITY] | [QUESTION] |
31| :-----: | -------------- | ------------------------------------------------- |
32| [1] | Data format | Input format? (nginx combined, JSON, CSV, custom) |
33| [2] | Large files | Files >100MB? Optimize for memory/performance? |
34| [3] | Error handling | Fail fast, continue with warnings, or retry? |
35| [4] | Portability | POSIX sh portability or bash 5.2+/5.3? |
36| [5] | Output format | Human-readable, JSON, or CSV? |
37
38**Guidance:**
39- *Architecture First:* Explain design, tool selection rationale, key tradeoffs before writing code.
40- *Data Format Routing:* JSON? `jq`. YAML? `yq eval`. CSV/TSV? `miller` (mlr). Interactive exploration? `jnv`.
41- *Template:* Reference `assets/templates/standard-template.sh` for production boilerplate.
42
43---
44## [2][STRICT_MODE]
45>**Dictum:** *Strict mode prevents silent failures.*
46
47<br>
48
49```bash
50#!/usr/bin/env bash
51set -Eeuo pipefail # -E = errtrace (ERR trap inherits into functions/subshells)
52shopt -s inherit_errexit # Command substitutions inherit errexit
53IFS=$'\n\t'
54```
55
56**Guidance:**
57- *Scope:* Every generated script includes this block. No exceptions.
58- *Disable:* Temporarily suppress — `output=$(cmd 2>&1) || handle_error "${output}"`.
59
60---
61## [3][FUNCTIONAL_STYLE]
62>**Dictum:** *Immutability and dispatch tables eliminate mutable state.*
63
64<br>
65
66| [INDEX] | [RULE] | [PATTERN] |
67| :-----: | --------------------- | -------------------------------------------------------------------------- |
68| [1] | Immutable locals | `local -r` for all non-mutating variables inside functions |
69| [2] | Immutable globals | `readonly` for all module-level constants |
70| [3] | Pure functions | Input via args, output via stdout or nameref (`local -n`), no global state |
71| [4] | Dispatch tables | `declare -Ar` for O(1) routing; `case/esac` only for pattern matching |
72| [5] | Higher-order | Pass function names as args; `local -n` nameref for array parameters |
73| [6] | Inline trivials | Single-use < 3 lines: inline at call site |
74| [7] | Brace grouping | `{ cmd1; cmd2; } > file` over `( ... )` (no subshell) |
75| [8] | No mutable counters | `${#arr[@]}`, `rg -c`, or `awk` pipelines for counting |
76| [9] | `mapfile`/`readarray` | Over `while read` loops for array population (3-5x faster) |
77| [10] | `printf` everywhere | Over `echo` (handles escapes, format strings, no ambiguity) |
78| [11] | `$(<file)` | Over `$(cat file)` (no fork) |
79| [12] | `printf -v` | `printf -v var '%(%F %T)T' -1` over `$(date ...)` (no subshell) |
80| [13] | Here-strings | `<<<` over `echo x \| cmd` pipelines |
81| [14] | BASH_REMATCH | `[[ str =~ regex ]]` + `${BASH_REMATCH[N]}` over `rg -oP` / `sd` |
82| [15] | Assoc set | `declare -Ar SET=([k]=1)` + `[[ -v SET[key] ]]` for O(1) membership |
83| [16] | IFS splitting | `IFS=, read -ra parts <<< "$csv"` over `cut` / `awk -F,` for simple delim |
84
85**Best-Practices:**
86- *Nameref Constraint:* Array variables cannot be namerefs, but namerefs can reference arrays.
87- *Dispatch Declaration:* `declare -Ar` assigns on declaration line; separate assignment fails for readonly.
88- *Structured Checks:* `declare -Ar CHECKS=([name]="pattern\|msg\|level")` + `IFS=\| read -r` for data-driven validation.
89
90---
91## [4][QUALITY_GATE]
92>**Dictum:** *Checklists prevent omissions.*
93
94<br>
95
96[VERIFY] Generation:
97- [ ] `#!/usr/bin/env bash` + `set -Eeuo pipefail` + `shopt -s inherit_errexit` + `IFS=$'\n\t'`.
98- [ ] All variables quoted: `"${var}"`.
99- [ ] Constants: `readonly UPPER_SNAKE`; locals: `local -r`; functions: `lower_snake()`.
100- [ ] `printf -v var '%(%F %T)T' -1` for timestamps (no `$(date)` subshell).
101- [ ] `[[ ]]` over `[ ]`; `<<<` over `echo |`; `<()` over temp files.
102- [ ] Cleanup: `trap cleanup EXIT` (single trap, EXIT covers normal + signal exits).
103- [ ] ShellCheck 0.11.0+ clean; no `eval` with user input; `$()` over backticks.
104- [ ] Usage/help with examples; post-generation summary with tool selection rationale.
105
106[REFERENCE]: [docs/bash-scripting-guide.md](./docs/bash-scripting-guide.md) — Language features, parameter expansion, arrays.
107[REFERENCE]: [docs/script-patterns.md](./docs/script-patterns.md) — Argument parsing, logging, parallel, retry.
108[REFERENCE]: [docs/text-processing-guide.md](./docs/text-processing-guide.md) — Tool selection, rg/awk/sd, performance.