bashintermediate

Log Rotation Management Script

Automate log rotation with compression, retention policies, and disk space monitoring in Bash.

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

LOG_DIR="/var/log/myapp"
MAX_AGE_DAYS=30
MAX_SIZE_MB=100
ARCHIVE_DIR="${LOG_DIR}/archive"

mkdir -p "$ARCHIVE_DIR"

# Rotate logs exceeding size limit
for log in "${LOG_DIR}"/*.log; do
  [ -f "$log" ] || continue
  size_mb=$(du -m "$log" | awk '{print $1}')
  if (( size_mb >= MAX_SIZE_MB )); then
    ts=$(date +%Y%m%d-%H%M%S)
    mv "$log" "${ARCHIVE_DIR}/$(basename "$log" .log)-${ts}.log"
    gzip "${ARCHIVE_DIR}/$(basename "$log" .log)-${ts}.log"
    touch "$log"
    echo "Rotated: $(basename "$log") (${size_mb}MB)"
  fi
done

# Delete old archives
find "$ARCHIVE_DIR" -name '*.gz' -mtime +${MAX_AGE_DAYS} -delete

# Disk space alert
usage=$(df "$LOG_DIR" | awk 'NR==2 {print $5}' | tr -d '%')
if (( usage > 90 )); then
  echo "WARNING: Disk usage at ${usage}%" >&2
fi

echo "Log rotation complete. Archive: $(du -sh "$ARCHIVE_DIR" | awk '{print $1}')"

Use Cases

  • Preventing disk space exhaustion from logs
  • Automated log archival with retention policies

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.