Prompt engineering techniques for generating reliable, production-safe bash scripts with AI.
Category: AI / GPT
The Golden Prompt Template
Write a bash script for Ubuntu 22.04 that:
1. [Primary task]
2. [Error handling requirement]
3. [Logging requirement]
4. [Safety requirement — e.g. dry-run mode]
Requirements:
- Use set -euo pipefail
- Include comments explaining non-obvious steps
- Test for required binaries before running
- Return exit code 0 on success, 1 on failure
Example: Disk Cleanup Script
Prompt sent to GPT:
Write a bash script for Ubuntu 22.04 that:
1. Finds log files older than 30 days in /var/log and /home/*/logs
2. Prints a summary of what will be deleted (dry-run by default)
3. Accepts a --delete flag to actually remove the files
4. Logs deleted files to /var/log/cleanup.log with timestamps
GPT output (condensed):
#!/bin/bash
set -euo pipefail
DRY_RUN=true
LOG="/var/log/cleanup.log"
DIRS=("/var/log" /home/*/logs)
[[ "${1:-}" == "--delete" ]] && DRY_RUN=false
for dir in "${DIRS[@]}"; do
[[ -d "$dir" ]] || continue
while IFS= read -r file; do
size=$(du -sh "$file" 2>/dev/null | cut -f1)
echo "[$(date)] Found: $file ($size)"
if ! $DRY_RUN; then
rm -f "$file"
echo "[$(date)] DELETED: $file" >> "$LOG"
fi
done < <(find "$dir" -type f -name "*.log" -mtime +30)
done
Common Follow-Up Prompts
- "Add a --help flag that explains usage"
- "Make it send a Slack notification on failure"
- "Rewrite this to work on both Ubuntu and RHEL"
- "Add a lock file so it can't run twice at the same time"
Validating AI-Generated Scripts
- Run
shellcheck script.shto catch common errors - Test with
bash -n script.shfor syntax errors - Run in a Docker container first:
docker run -it ubuntu:22.04 bash