Linux Shell Scriptor
Overview
Generates production-ready bash scripts from plain English descriptions. Every script follows Linux best practices: strict mode, structured error handling, timestamped logging, secure defaults, dry-run support, and a built-in usage function.
Language: Respond in the user's language. Script comments and variable names default to English.
When to Use
- User describes any task they want automated as a shell script
- User says "write a bash script", "create a shell script", "script to…"
- Backup, monitoring, deployment, cleanup, health check, cron job, report, alerting
- User wants to automate any repetitive sysadmin or DevOps task
When NOT to Use
- User wants a Python / Perl / Ruby script → general coding
- User wants to audit an existing config → /linux-config-auditor
- User wants to configure a service → /linux-config-auditor
- User wants to set up cron scheduling only → /linux-cron-manager
Clarification Protocol
If the user's description is missing critical details, ask one question at a time. Never ask more than two clarifying questions total before generating. Start generating and list assumptions if the use case is reasonably clear.
| Missing info |
Question to ask |
| Target distro |
"Which Linux distro does this run on (Ubuntu, RHEL, Alpine…)?" |
| Run as which user |
"Should the script run as root or a regular user?" |
| Triggered how |
"Is this run manually, by cron, or triggered by another process?" |
| On failure behavior |
"On failure, should it exit silently, log, or send a notification?" |
| Destructive actions |
"Should there be a --dry-run mode to preview changes before applying?" |
Script Quality Standards
Every script MUST contain all of the following:
| Element |
Implementation |
| Shebang + strict mode |
#!/usr/bin/env bash and set -euo pipefail |
| Script header |
Name, version, purpose, date in a comment block |
usage() function |
Flags, arguments, examples, exit codes |
| Logging helpers |
log(), warn(), error() functions writing to stderr with timestamps |
| Argument parsing |
getopts or manual flag loop with validation and usage on bad args |
| Dependency check |
command -v <tool> >/dev/null for every external command used |
| Trap + cleanup |
trap cleanup EXIT to remove temp files and restore state; also trap 'error "Script interrupted"; cleanup; exit 130' INT TERM to handle kills |
| Idempotent logic |
Safe to run multiple times wherever possible |
| Dry-run mode |
--dry-run / -n flag for any script that modifies files or services |
| No hardcoded secrets |
Credentials via env vars or config files only; never inline |
| Quoted variables |
All variable expansions in double quotes: "$var" |
Templates by Use Case
Backup Script
- Defines SOURCE_DIR, DEST_DIR, RETENTION_DAYS
- Uses
rsync -az --delete or tar -czf based on size
- Verifies backup integrity (checksum or restore test)
- Prunes old backups with
find … -mtime +N -delete
- Lock file to prevent concurrent runs (
flock)
- Logs start/end/size, emails or writes to syslog on failure
Monitoring / Health Check
- Checks disk usage (
df), memory (free), CPU load (uptime), and key services (systemctl is-active)
- User-configurable thresholds (DISK_WARN=80, DISK_CRIT=90)
- Outputs OK / WARN / CRIT per check
- Optional Nagios-compatible exit codes (0/1/2)
- Can write to a status file for polling
Deployment Script
- Pull latest code (
git pull or artifact fetch)
- Run build step if needed
- Run DB migrations
- Swap symlink or restart service
- On failure: rollback and log exactly what failed
- Appends to a deployment log with timestamp and git SHA
System Maintenance
- Package updates (
apt/yum/dnf) with pre-check for reboot requirement
- Old file cleanup (
find /tmp -mtime +7 -delete)
- Journal/log rotation trigger
- Creates a maintenance report in
/var/log/maintenance.log
Log Management / Report
- Parses a log file with
grep/awk/sed patterns provided by user
- Counts occurrences, extracts fields, detects anomalies
- Outputs a summary report to stdout or a file
- Optionally archives processed logs
Database Maintenance
- Connects using env vars (never hardcoded credentials)
- PostgreSQL:
pg_dump, VACUUM, ANALYZE, pg_stat_activity monitoring
- MySQL:
mysqldump, optimize tables, check binary log size
- Redis:
redis-cli INFO, BGSAVE, key count / memory stats
- Sends result summary to log file; alerts on non-zero exit
TLS Certificate Expiry Monitoring
- Checks each domain with
openssl s_client / openssl x509 -enddate
- Calculates days until expiry
- Sends email alert if expiry < 30 days (warning) or < 7 days (critical)
- Logs results; exits 0 on success, 1 on critical
- Can trigger
certbot renew automatically if installed
Service Health Check with Auto-Recovery
- Uses
systemctl is-active to check service status
- Restarts failed service once, waits 10s, checks again
- Sends alert if still down after restart attempt
- Logs all restart events with timestamp
Security Rules
These are non-negotiable and must appear in every generated script:
- No
eval with user input — ever
- Quote every variable expansion:
"$var", "${array[@]}"
- Temp files via
mktemp — never predictable paths like /tmp/script.tmp
- Validate file path inputs — check for
.. traversal before using
- Restrictive umask for sensitive output:
umask 077 before writing credentials or keys
- Avoid unnecessary
sudo — document when privilege escalation is needed and why
set -euo pipefail — always; prevents silent failures from masked errors
Output Format
- Write the script to
./scripts/<task-name>.sh
- Also print the script in a fenced
bash code block so the user can review it before running
- Below the script, list any assumptions made (distro, user, paths, thresholds)
- Show:
# Syntax check before first run
bash -n scripts/your-script.sh
# Make executable
chmod +x scripts/your-script.sh
# Test with dry-run (if script supports it)
./scripts/your-script.sh --dry-run
- Suggest next steps based on script type
Next Steps (always include after output)
Syntax check: bash -n scripts/your-script.sh
ShellCheck: shellcheck scripts/your-script.sh (install: apt install shellcheck)
If recurring: Add to cron with /linux-cron-manager or a systemd timer with /linux-systemd-manager
If security-sensitive: Review the host with /linux-security-hardener
If it reads config files: Audit those configs with /linux-config-auditor
1---2name: linux-shell-scriptor3description: Use when user wants to write, generate, or create a bash or shell script for any Linux task — backups, monitoring, deployment, automation, cron jobs, health checks, system maintenance, log rotation, or any described sysadmin use case.4---56# Linux Shell Scriptor78## Overview910Generates production-ready bash scripts from plain English descriptions. Every script follows Linux best practices: strict mode, structured error handling, timestamped logging, secure defaults, dry-run support, and a built-in usage function.1112**Language:** Respond in the user's language. Script comments and variable names default to English.1314---1516## When to Use1718- User describes any task they want automated as a shell script19- User says "write a bash script", "create a shell script", "script to…"20- Backup, monitoring, deployment, cleanup, health check, cron job, report, alerting21- User wants to automate any repetitive sysadmin or DevOps task2223## When NOT to Use2425- User wants a Python / Perl / Ruby script → general coding26- User wants to audit an existing config → /linux-config-auditor27- User wants to configure a service → /linux-config-auditor28- User wants to set up cron scheduling only → /linux-cron-manager2930---3132## Clarification Protocol3334If the user's description is missing critical details, ask **one question at a time**. Never ask more than two clarifying questions total before generating. Start generating and list assumptions if the use case is reasonably clear.3536| Missing info | Question to ask |37|-------------|----------------|38| Target distro | "Which Linux distro does this run on (Ubuntu, RHEL, Alpine…)?" |39| Run as which user | "Should the script run as root or a regular user?" |40| Triggered how | "Is this run manually, by cron, or triggered by another process?" |41| On failure behavior | "On failure, should it exit silently, log, or send a notification?" |42| Destructive actions | "Should there be a `--dry-run` mode to preview changes before applying?" |4344---4546## Script Quality Standards4748Every script MUST contain all of the following:4950| Element | Implementation |51|---------|----------------|52| Shebang + strict mode | `#!/usr/bin/env bash` and `set -euo pipefail` |53| Script header | Name, version, purpose, date in a comment block |54| `usage()` function | Flags, arguments, examples, exit codes |55| Logging helpers | `log()`, `warn()`, `error()` functions writing to stderr with timestamps |56| Argument parsing | `getopts` or manual flag loop with validation and `usage` on bad args |57| Dependency check | `command -v <tool> >/dev/null` for every external command used |58| Trap + cleanup | `trap cleanup EXIT` to remove temp files and restore state; also `trap 'error "Script interrupted"; cleanup; exit 130' INT TERM` to handle kills |59| Idempotent logic | Safe to run multiple times wherever possible |60| Dry-run mode | `--dry-run` / `-n` flag for any script that modifies files or services |61| No hardcoded secrets | Credentials via env vars or config files only; never inline |62| Quoted variables | All variable expansions in double quotes: `"$var"` |6364---6566## Templates by Use Case6768### Backup Script69- Defines SOURCE_DIR, DEST_DIR, RETENTION_DAYS70- Uses `rsync -az --delete` or `tar -czf` based on size71- Verifies backup integrity (checksum or restore test)72- Prunes old backups with `find … -mtime +N -delete`73- Lock file to prevent concurrent runs (`flock`)74- Logs start/end/size, emails or writes to syslog on failure7576### Monitoring / Health Check77- Checks disk usage (`df`), memory (`free`), CPU load (`uptime`), and key services (`systemctl is-active`)78- User-configurable thresholds (DISK_WARN=80, DISK_CRIT=90)79- Outputs OK / WARN / CRIT per check80- Optional Nagios-compatible exit codes (0/1/2)81- Can write to a status file for polling8283### Deployment Script84- Pull latest code (`git pull` or artifact fetch)85- Run build step if needed86- Run DB migrations87- Swap symlink or restart service88- On failure: rollback and log exactly what failed89- Appends to a deployment log with timestamp and git SHA9091### System Maintenance92- Package updates (`apt`/`yum`/`dnf`) with pre-check for reboot requirement93- Old file cleanup (`find /tmp -mtime +7 -delete`)94- Journal/log rotation trigger95- Creates a maintenance report in `/var/log/maintenance.log`9697### Log Management / Report98- Parses a log file with `grep`/`awk`/`sed` patterns provided by user99- Counts occurrences, extracts fields, detects anomalies100- Outputs a summary report to stdout or a file101- Optionally archives processed logs102103### Database Maintenance104- Connects using env vars (never hardcoded credentials)105- PostgreSQL: `pg_dump`, `VACUUM`, `ANALYZE`, `pg_stat_activity` monitoring106- MySQL: `mysqldump`, optimize tables, check binary log size107- Redis: `redis-cli INFO`, `BGSAVE`, key count / memory stats108- Sends result summary to log file; alerts on non-zero exit109110### TLS Certificate Expiry Monitoring111- Checks each domain with `openssl s_client` / `openssl x509 -enddate`112- Calculates days until expiry113- Sends email alert if expiry < 30 days (warning) or < 7 days (critical)114- Logs results; exits 0 on success, 1 on critical115- Can trigger `certbot renew` automatically if installed116117### Service Health Check with Auto-Recovery118- Uses `systemctl is-active` to check service status119- Restarts failed service once, waits 10s, checks again120- Sends alert if still down after restart attempt121- Logs all restart events with timestamp122123---124125## Security Rules126127These are non-negotiable and must appear in every generated script:128129- **No `eval` with user input** — ever130- **Quote every variable expansion:** `"$var"`, `"${array[@]}"`131- **Temp files via `mktemp`** — never predictable paths like `/tmp/script.tmp`132- **Validate file path inputs** — check for `..` traversal before using133- **Restrictive umask for sensitive output:** `umask 077` before writing credentials or keys134- **Avoid unnecessary `sudo`** — document when privilege escalation is needed and why135- **`set -euo pipefail`** — always; prevents silent failures from masked errors136137---138139## Output Format1401411. Write the script to `./scripts/<task-name>.sh`1422. **Also print** the script in a fenced `bash` code block so the user can review it before running1433. Below the script, list any **assumptions made** (distro, user, paths, thresholds)1444. Show:145146```bash147# Syntax check before first run148bash -n scripts/your-script.sh149150# Make executable151chmod +x scripts/your-script.sh152153# Test with dry-run (if script supports it)154./scripts/your-script.sh --dry-run155```1561575. Suggest next steps based on script type158159---160161## Next Steps (always include after output)162163> **Syntax check:** `bash -n scripts/your-script.sh`164> **ShellCheck:** `shellcheck scripts/your-script.sh` (install: `apt install shellcheck`)165> **If recurring:** Add to cron with `/linux-cron-manager` or a systemd timer with `/linux-systemd-manager`166> **If security-sensitive:** Review the host with `/linux-security-hardener`167> **If it reads config files:** Audit those configs with `/linux-config-auditor`