- Posted on
- • Artificial Intelligence
Artificial Intelligence That Writes Complete Bash Automation Projects
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence That Writes Complete Bash Automation Projects
What if you could brief an AI with: “Create a robust backup and log-rotation toolkit with tests, linting, and a Makefile,” then watch a full Bash project scaffold itself—scripts, tests, docs, CI hooks and all?
This isn’t sci‑fi. With a tiny command-line harness and a few discipline tools (shellcheck, shfmt, bats), you can direct an LLM to draft complete, testable Bash automation—then iterate safely, fast.
Below is a practical blueprint: why this works, how to set it up, and a repeatable workflow you can use today.
Why AI for Bash Is Valid (and Useful)
Bash isn’t going anywhere. It’s still the lingua franca for glue code, packaging, CI/CD, and fleet administration. The repetitive pieces—scaffolding, boilerplate, docstrings, argument parsing—are perfect for AI to draft.
LLMs excel at patterns. When you ask for “POSIX-ish scripts with set -euo pipefail, shellcheck-clean, bats tests,” you’re giving the AI a playbook it can follow consistently.
Guardrails keep you safe. Static checks (shellcheck), formatters (shfmt), tests (bats), and containerized or throwaway environments neutralize risk. The AI proposes; your toolchain disposes (of bad ideas).
Prerequisites: Install the Basics
These tools let you generate, verify, and iterate on AI-produced Bash code.
git, curl, jq: for fetching, HTTPing, and JSON parsing
shellcheck: static analysis
shfmt: formatting
bats: Bash tests
make: orchestration
Install with your package manager:
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y git curl jq shellcheck shfmt bats make
- Fedora/RHEL/CentOS (dnf):
sudo dnf install -y git curl jq ShellCheck shfmt bats make
- openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y git curl jq ShellCheck shfmt bats make
Optionally, for a local model runner (no cloud key required), install Ollama:
curl -fsSL https://ollama.com/install.sh | sh
You’ll also need an API key if you use a hosted model:
export OPENAI_API_KEY="your_api_key_here"
The Core Idea: A Minimal AI-to-Bash Project Pipeline
We’ll create a tiny harness with:
a prompt file that describes the project you want,
a generator script that calls an LLM,
a safe file-applier that writes only what the AI returns between explicit file markers,
Make targets to format, lint, and test.
1) Project Scaffold
Create a working directory and seed files:
mkdir -p ai-bash-project/{prompts,scripts,tests}
cd ai-bash-project
Makefile:
cat > Makefile <<'EOF'
SHELL := /usr/bin/env bash
.PHONY: deps fmt lint test generate apply ci
deps:
@command -v shellcheck >/dev/null || { echo "shellcheck missing"; exit 1; }
@command -v shfmt >/dev/null || { echo "shfmt missing"; exit 1; }
@command -v bats >/dev/null || { echo "bats missing"; exit 1; }
@command -v jq >/dev/null || { echo "jq missing"; exit 1; }
@command -v curl >/dev/null || { echo "curl missing"; exit 1; }
@echo "Dependencies OK"
fmt:
shfmt -w -i 2 -sr .
lint:
shellcheck -S style $(git ls-files '*.sh' 2>/dev/null || true)
test:
bats -r tests || true
generate:
@[ -n "$$OPENAI_API_KEY" ] || { echo "OPENAI_API_KEY is not set"; exit 1; }
./scripts/ai_generate.sh prompts/request.md > out/ai.txt
@echo "AI output saved to out/ai.txt"
apply:
./scripts/apply_ai_files.sh out/ai.txt
@echo "Applied AI files"
ci: fmt lint test
EOF
Gitignore and output folder:
mkdir -p out
printf "out/\n*.swp\n" > .gitignore
A seed test folder:
mkdir -p tests
2) AI File-Marker Convention and Safe Writer
We’ll tell the AI to emit files using explicit markers:
Start:
--8<-- file:start path=RELATIVE/PATHEnd:
--8<-- file:end
Example AI output snippet:
--8<-- file:start path=scripts/backup.sh
#!/usr/bin/env bash
set -euo pipefail
# ...
--8<-- file:end
File applier (safe, minimal parsing):
cat > scripts/apply_ai_files.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
src="${1:-/dev/stdin}"
current=""
tmpfile=""
cleanup() { [[ -n "${tmpfile:-}" && -f "$tmpfile" ]] && rm -f "$tmpfile"; }
trap cleanup EXIT
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ "$line" =~ ^--8\<\-\-\ file:start\ path=(.+)$ ]]; then
current="${BASH_REMATCH[1]}"
mkdir -p "$(dirname "$current")"
tmpfile="$(mktemp)"
> "$tmpfile"
collecting=1
continue
fi
if [[ "${collecting:-0}" -eq 1 && "$line" =~ ^--8\<\-\-\ file:end$ ]]; then
mv "$tmpfile" "$current"
tmpfile=""
collecting=0
current=""
continue
fi
if [[ "${collecting:-0}" -eq 1 ]]; then
printf '%s\n' "$line" >> "$tmpfile"
fi
done < "$src"
EOF
chmod +x scripts/apply_ai_files.sh
3) LLM Generator Scripts (Cloud and Local)
OpenAI-based generator:
cat > scripts/ai_generate.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
prompt_file="${1:?Usage: $0 prompts/request.md}"
: "${OPENAI_API_KEY:?OPENAI_API_KEY not set}"
system_msg=$'You are a senior Bash automation engineer. Generate a complete Bash project using ONLY file sections delimited by:\n--8<-- file:start path=RELATIVE/PATH\n...content...\n--8<-- file:end\n\nRequirements:\n- Safe Bash (set -euo pipefail, IFS=$\' \\t\\n\')\n- shellcheck-clean, shfmt-friendly\n- Clear usage/help (-h/--help)\n- No destructive commands without explicit path guards\n- Include tests (bats) and README with examples\n- Keep responses under 1500 lines total\n- Do not include commentary outside file sections.'
jq -n \
--arg sys "$system_msg" \
--arg user "$(cat "$prompt_file")" \
'{
model: "gpt-4o-mini",
temperature: 0.2,
messages: [
{role: "system", content: $sys},
{role: "user", content: $user}
]
}' \
| curl -fsS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer '"$OPENAI_API_KEY"'" \
-d @- \
| jq -r '.choices[0].message.content'
EOF
chmod +x scripts/ai_generate.sh
Optional: local model via Ollama (if installed):
cat > scripts/ai_generate_ollama.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
prompt_file="${1:?Usage: $0 prompts/request.md}"
model="${2:-qwen2.5-coder:latest}" # pick a code-capable model available locally
system_msg=$'You are a senior Bash automation engineer. Output ONLY file sections using the markers:\n--8<-- file:start path=RELATIVE/PATH\n...content...\n--8<-- file:end\nFollow shellcheck/shfmt best practices and include bats tests + README.'
payload=$(jq -n --arg sm "$system_msg" --arg pm "$(cat "$prompt_file")" '{prompt: ($sm + "\n\n" + $pm), model: "'$model'"}')
curl -fsS http://localhost:11434/api/generate \
-H "Content-Type: application/json" \
-d "$payload" \
| jq -r '.response' \
| sed '/^\s*$/N;/^\n$/D' # compact
EOF
chmod +x scripts/ai_generate_ollama.sh
4) A Good Prompt (The “Spec”)
Great prompts act like an engineering ticket. Here’s a real-world example request for a backup + log rotation project:
cat > prompts/request.md <<'EOF'
Goal: A Bash-based backup and log-rotation project for Linux servers.
Scope:
- scripts/backup.sh: tar/gzip a source directory to a destination with date-stamped filenames.
- scripts/rotate.sh: rotate logs in /var/log/myapp (configurable) with retention policy (e.g., keep 7).
- scripts/common.sh: shared helpers (logging, error handling, path validation).
- tests/*.bats: tests for backup and rotation.
- README.md: setup, usage examples, cron examples, safety notes.
- .editorconfig and .shellcheckrc for consistency.
Requirements:
- Bash with set -euo pipefail and safe IFS.
- shellcheck-clean, shfmt-friendly.
- Provide usage (-h/--help) and exit codes.
- No destructive rm without guarding (e.g., forbid "/" or empty vars).
- Support ENV overrides: SRC_DIR, DEST_DIR, RETAIN_DAYS.
- Include Makefile targets: fmt, lint, test.
Output format:
Use ONLY these markers per file:
--8<-- file:start path=RELATIVE/PATH
...file content...
--8<-- file:end
EOF
5) Generate → Apply → Verify
Run the loop:
make deps
./scripts/ai_generate.sh prompts/request.md > out/ai.txt
./scripts/apply_ai_files.sh out/ai.txt
make fmt
make lint
make test
If lint/tests fail, iterate: refine prompts/request.md, regenerate, and re-apply. Commit checkpoints frequently:
git init
git add .
git commit -m "Initial AI-generated backup project"
Real-World Example: What You’ll Get
After one pass, you should expect:
scripts/common.sh with logging functions, argument parsing helpers, safe rm wrappers
scripts/backup.sh implementing date-stamped archives and exclusion patterns
scripts/rotate.sh handling N-day retention with checks
tests/backup.bats and tests/rotate.bats confirming help text, dry-runs, and key behaviors
README.md containing examples and cron suggestions like:
0 2 * * * /path/to/repo/scripts/backup.sh -s /srv/data -d /srv/backups >>/var/log/backup.log 2>&1
Then your toolchain locks it down:
shfmt normalizes style
shellcheck catches quoting or unguarded globs
bats proves basic behavior still holds after edits
Actionable Tips for Better Results
1) Be explicit about file boundaries and policies
Always require the AI to use the
--8<-- file:start/endmarkers.Tell it to avoid dangerous patterns and to document any command that writes or deletes.
2) Keep temperature low, demand tests
Use
temperature: 0.2–0.3for consistency.Ask for bats tests so you can verify behavior quickly.
3) Bake in safety checks
Enforce
set -euo pipefailand safe IFS.Demand functions that validate paths before deletes or moves.
4) Iterate in small deltas
Start with one cohesive feature (e.g., backup only).
Add rotation, retention policies, and systemd units later.
5) Consider local models for privacy
If data sensitivity is high, try
scripts/ai_generate_ollama.shwith a strong local code model.The flow is identical.
Common Pitfalls (and Fixes)
AI returns prose outside markers
Fix: Strengthen the system prompt: “Output ONLY file sections…” and reject runs without markers.Paths or permissions issues
Fix: Ensure your apply script doesmkdir -pbefore writing. Run in a dev directory, not prod.Flaky or incomplete tests
Fix: Ask the AI to add negative tests (bad input, missing dirs) and dry-run modes. Manually expand tests over time.Overly clever one-liners
Fix: Request readability over brevity and require shellcheck-clean output.
Conclusion and Next Steps
AI can draft a complete Bash automation project in minutes, but reliability comes from your guardrails—lint, format, tests—and from clear, repeatable prompts.
Do this next:
Install the prerequisites (apt/dnf/zypper commands above).
Copy the Makefile and scripts into a fresh repo.
Write a focused prompt in prompts/request.md.
Run:
make deps && make generate && make apply && make ci
In an hour, you’ll have a working, testable Bash automation project—built by AI, verified by your toolchain, and ready for real infrastructure.
Have a use case in mind? Point the generator at it and ship your first AI-assisted Bash project today.