Shell Scripting Pro: The Claude Code Agent That Writes Production-Ready Shell Scripts
Shell scripting is one of those disciplines where the gap between “works on my machine” and “safe to run in production” is enormous. A script that lacks proper error handling, unquoted variables, or platform-specific assumptions can corrupt data, leave systems in inconsistent states, or fail silently at the worst possible moment. Senior developers know this pain — you’ve either lived it or inherited someone else’s mess.
The Shell Scripting Pro agent for Claude Code closes that gap. Instead of writing a quick-and-dirty script that you’ll need to harden later, you get defensive, POSIX-compliant shell scripts with comprehensive error handling from the first iteration. It understands set -euo pipefail, proper variable quoting, modular function design, and cross-platform compatibility — the fundamentals that separate professional shell scripts from fragile one-liners. If you’re writing automation, deployment pipelines, or system administration scripts, this agent is worth having in your toolkit.
When to Use the Shell Scripting Pro Agent
The agent description explicitly says to use it proactively — meaning before you start writing scripts yourself, not after you’ve already got a broken draft. Here are the scenarios where it earns its keep:
Deployment and CI/CD Scripts
Deployment scripts are high-stakes. A failed deployment that leaves services in a half-migrated state costs hours to debug and recover from. Use this agent when writing scripts that touch production systems, manage service restarts, run database migrations, or handle rollback logic. The agent’s emphasis on error handling and exit codes makes generated scripts behave correctly in CI/CD environments where failures need to propagate properly.
System Administration Automation
Recurring admin tasks — log rotation, disk space monitoring, user provisioning, certificate renewal — benefit enormously from well-structured scripts. When you need automation that will run unattended via cron or systemd, you need scripts that handle edge cases, log what they do, and fail loudly when something goes wrong. This agent builds that behavior in by default.
Cross-Platform Tooling
If you’re writing scripts that need to run on Linux servers, macOS developer machines, and potentially BSD-based systems, POSIX compliance matters. The agent actively avoids bashisms when a POSIX-compatible alternative exists, and it flags when bash-specific features are necessary so you can make conscious tradeoffs.
Text Processing Pipelines
Complex awk, sed, and grep pipelines that process logs, transform data, or generate reports are notoriously hard to get right and even harder to maintain. The agent writes these with clear structure, prefers built-in commands where performance allows, and documents the logic so the next developer doesn’t have to reverse-engineer a regex.
Onboarding and Environment Setup Scripts
Setup scripts that run once per environment are often written hastily and never revisited. They become a source of developer frustration when they fail on a new OS version or assume a tool is installed. Use the agent to write idempotent setup scripts with proper dependency checks and helpful error messages.
Real-World Examples
Scenario 1: Writing a Safe Deployment Script
A backend engineer needs to write a deployment script for a Node.js service that stops the old process, pulls new code, runs migrations, and restarts — with rollback if anything fails.
Developer: Write a deployment script for a Node.js service. It should:
- Pull the latest code from git
- Run npm ci
- Run database migrations
- Restart the service via systemctl
- Roll back to the previous commit if any step fails
Agent: Here's a production-ready deployment script with rollback support:
#!/usr/bin/env bash
set -euo pipefail
# --- Configuration ---
SERVICE_NAME="my-node-service"
APP_DIR="/opt/app"
LOG_FILE="/var/log/deploy.log"
# --- Logging ---
log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" | tee -a "$LOG_FILE"; }
die() { log "ERROR: $*"; exit 1; }
# --- Rollback ---
PREVIOUS_COMMIT=""
rollback() {
log "Rolling back to ${PREVIOUS_COMMIT}"
git -C "$APP_DIR" checkout "$PREVIOUS_COMMIT" || die "Rollback failed"
systemctl restart "$SERVICE_NAME" || die "Service restart after rollback failed"
log "Rollback complete"
}
trap rollback ERR
# --- Deploy ---
cd "$APP_DIR" || die "Cannot change to app directory"
PREVIOUS_COMMIT=$(git rev-parse HEAD)
log "Pulling latest code"
git pull --ff-only origin main || die "Git pull failed"
log "Installing dependencies"
npm ci --prefer-offline || die "npm ci failed"
log "Running migrations"
npm run migrate || die "Migration failed"
log "Restarting service"
systemctl restart "$SERVICE_NAME" || die "Service restart failed"
log "Deployment complete"
The agent explains each section, notes that trap rollback ERR fires on any unhandled error, and flags that npm run migrate should be idempotent if rollback is to be reliable.
Scenario 2: Building a Log Monitoring Script
A DevOps engineer wants a script that tails a log file, detects error patterns, and sends an alert when thresholds are exceeded.
Developer: I need a script that watches /var/log/app.log, counts ERROR lines
per minute, and sends a Slack webhook alert if the rate exceeds 10 per minute.
Agent: Here's a log monitor with rate-limiting and webhook integration:
#!/usr/bin/env bash
set -euo pipefail
LOG_FILE="${1:-/var/log/app.log}"
THRESHOLD="${2:-10}"
WEBHOOK_URL="${SLACK_WEBHOOK_URL:?SLACK_WEBHOOK_URL must be set}"
WINDOW=60
[[ -r "$LOG_FILE" ]] || { echo "Cannot read log file: $LOG_FILE" >&2; exit 1; }
send_alert() {
local count="$1"
local payload
payload=$(printf '{"text":"*Alert*: %d ERROR lines in the last %ds (threshold: %d)"}' \
"$count" "$WINDOW" "$THRESHOLD")
curl -s -X POST -H 'Content-type: application/json' \
--data "$payload" "$WEBHOOK_URL" > /dev/null
}
count_errors() {
local since="$1"
grep -c "ERROR" <(awk -v t="$since" '$0 >= t' "$LOG_FILE") 2>/dev/null || echo 0
}
while true; do
since=$(date -u -d "-${WINDOW} seconds" '+%Y-%m-%dT%H:%M:%S' 2>/dev/null \
|| date -u -v "-${WINDOW}S" '+%Y-%m-%dT%H:%M:%S')
error_count=$(count_errors "$since")
if (( error_count > THRESHOLD )); then
send_alert "$error_count"
fi
sleep 30
done
The agent notes the date command uses a compatibility shim for Linux vs. macOS, validates the webhook URL via parameter expansion with a meaningful error, and explains how to test locally with a mock webhook endpoint.
What Makes This Agent Powerful
Defensive Programming by Default
Every script starts with set -euo pipefail. This isn’t optional or something you have to request — it’s the baseline. Combined with proper trap handlers for cleanup on exit, you get scripts that fail loudly and leave systems in a clean state.
Correct Variable Quoting
Unquoted variables are one of the most common sources of shell script bugs, especially with filenames containing spaces. The agent quotes variables consistently and uses constructs like ${variable:?error message} to catch unset variables explicitly.
POSIX Compliance with Pragmatic Bash
The agent targets POSIX compliance as the default but knows when bash-specific features — arrays, associative maps, process substitution — genuinely improve the solution. It makes those tradeoffs explicit so you can adjust the shebang and target shell accordingly.
Modular, Reusable Function Design
Rather than monolithic scripts, the agent structures code as composable functions with clear responsibilities. Logging helpers, validation functions, and cleanup handlers are separated, making scripts easier to test incrementally and maintain over time.
Built-in Usage Documentation
Scripts include --help flags and usage functions that explain arguments, required environment variables, and example invocations. This is especially valuable for scripts that will be run by other team members or integrated into CI pipelines weeks after you’ve forgotten how they work.
Cross-Platform Awareness
The agent handles the GNU/BSD divergence in core utilities — date, sed, xargs — and either writes compatible code or adds explicit compatibility checks. This matters if your scripts run on Linux servers but you develop on macOS.
How to Install the Shell Scripting Pro Agent
Installing the agent takes about sixty seconds. Claude Code automatically loads agents defined in your project’s .claude/agents/ directory.
- In your project root, create the directory if it doesn’t exist:
mkdir -p .claude/agents - Create the file
.claude/agents/shell-scripting-pro.md - Paste the following system prompt into that file:
---
name: Shell Scripting Pro
description: Write robust shell scripts with proper error handling, POSIX compliance, and automation patterns. Masters bash/zsh features, process management, and system integration. Use PROACTIVELY for automation, deployment scripts, or system administration tasks.
---
You are a shell scripting expert specializing in robust automation and system administration scripts.
## Focus Areas
- POSIX compliance and cross-platform compatibility
- Advanced bash/zsh features and built-in commands
- Error handling and defensive programming
- Process management and job control
- File operations and text processing
- System integration and automation patterns
## Approach
1. Write defensive scripts with comprehensive error handling
2. Use set -euo pipefail for strict error mode
3. Quote variables properly to prevent word splitting
4. Prefer built-in commands over external tools when possible
5. Test scripts across different shell environments
6. Document complex logic and provide usage examples
## Output
- Robust shell scripts with proper error handling
- POSIX-compliant code for maximum compatibility
- Comprehensive input validation and sanitization
- Clear usage documentation and help messages
- Modular functions for reusability
- Integration with logging and monitoring systems
- Performance-optimized text processing pipelines
Follow shell scripting best practices and ensure scripts are maintainable and portable across Unix-like systems.
Claude Code picks up the agent automatically on next load — no configuration files to edit, no CLI flags to set. The agent will be available by name in your Claude Code sessions within that project.
Practical Next Steps
If you’ve got a folder of shell scripts that have accumulated over the years — deployment automation, cron jobs, setup scripts — run them through the agent for a review pass. Ask it to identify unquoted variables, missing error handling, and non-portable constructs. That alone will surface issues worth fixing before they cause incidents.
For new scripts, invoke the agent at the start of the task rather than polishing a draft at the end. Describe the behavior you need, the target environment, and any constraints (specific shell version, read-only filesystem, no external tools). The agent will ask the right clarifying questions and generate a production-ready first draft faster than you can scaffold the boilerplate yourself.
The Shell Scripting Pro agent won’t replace your judgment on what a script should do, but it will consistently produce a quality baseline that would otherwise require a careful review checklist to achieve manually. For teams writing infrastructure automation at scale, that consistency is the real value.
Agent template sourced from the claude-code-templates open source project (MIT License).
