Describe what you need in plain English, get a hardened bash script with error handling, help text, and cleanup.

Prompt

Write a production-ready bash script that does the following:

[DESCRIBE WHAT THE SCRIPT SHOULD DO]

Requirements:
- Use set -euo pipefail
- Include a usage/help function (-h flag)
- Validate all inputs before proceeding
- Use cleanup traps for temporary files
- Log actions to stderr, output results to stdout
- Use descriptive variable names
- Add inline comments only for non-obvious logic

Example

Input:

Write a production-ready bash script that backs up a PostgreSQL
database to S3, compresses it, and deletes backups older than 30 days.

Output:

#!/usr/bin/env bash
set -euo pipefail

DB_NAME="${1:?Usage: $0 <database_name> <s3_bucket>}"
S3_BUCKET="${2:?Usage: $0 <database_name> <s3_bucket>}"
RETENTION_DAYS=30
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
DUMP_FILE=$(mktemp "/tmp/${DB_NAME}_${TIMESTAMP}_XXXXX.sql.gz")

cleanup() { rm -f "$DUMP_FILE"; }
trap cleanup EXIT

log() { echo "[$(date +%H:%M:%S)] $*" >&2; }

log "Dumping ${DB_NAME}..."
pg_dump "$DB_NAME" | gzip > "$DUMP_FILE"

log "Uploading to s3://${S3_BUCKET}/${DB_NAME}/"
aws s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${DB_NAME}/${DB_NAME}_${TIMESTAMP}.sql.gz"

log "Removing backups older than ${RETENTION_DAYS} days..."
aws s3 ls "s3://${S3_BUCKET}/${DB_NAME}/" \
  | awk -v cutoff="$(date -d "-${RETENTION_DAYS} days" +%Y-%m-%d)" '$1 < cutoff {print $4}' \
  | xargs -I{} aws s3 rm "s3://${S3_BUCKET}/${DB_NAME}/{}"

log "Done."