bashintermediate
Log Rotation Management Script
Automate log rotation with compression, retention policies, and disk space monitoring in Bash.
bashPress ⌘/Ctrl + Shift + C to copy
#!/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.
bashintermediate
Database Backup Script with Rotation
Automated PostgreSQL backup script with compression, rotation, and optional S3 upload.
Best for: Automated nightly database backups
#backup#postgres
bashintermediate
Makefile for DevOps Automation
Makefile with common DevOps targets for building, testing, deploying, and managing Docker containers.
Best for: Standardizing developer commands across teams
#makefile#automation
bashintermediate
Bash Parallel Jobs — Run Tasks Concurrently
Execute multiple shell commands in parallel with job control, exit code checking, and max concurrency.
Best for: Running CI checks in parallel for faster builds
#bash#parallel
bashintermediate
Bash ETL Pipeline Script
Build a complete ETL script in Bash with logging, error handling, notifications, and idempotent runs.
Best for: Automating daily data extract and load jobs
#bash#etl