← Back to Blog
Code Snippets August 6, 2026

Code Snippet — August 6, 2026 ### Bash: Log Rotation with Compression, Re

🐚 Code Snippet — August 6, 2026

Bash: Log Rotation with Compression, Retention & Signal-Based Reloading



logrotate runs on a schedule, doesn't watch file size in real time, and doesn't signal your app to reopen its log handle — you lose log lines between rotation and restart. This script does size-based triggers (rotate when > N MB), continuous watch mode (--watch, no cron needed), gzip/bzip2 compression, configurable retention (--keep N), SIGUSR1 reload via PID file (app reopens log, zero lost lines), atomic copy + truncate (no inode swap), and dry-run mode. Pure Bash — works in systemd, Docker, or standalone.

# One-shot rotation
./rotate_logs.sh --max-size 100 --keep 5 --compress gzip \
  --app-pid /var/run/myapp.pid /var/log/myapp/server.log

# Continuous watch mode — no cron needed
nohup ./rotate_logs.sh --watch --max-size 256 --compress gzip \
  /var/log/myapp/*.log &

# Dry-run to preview
./rotate_logs.sh --dry-run --verbose --max-size 100 \
  /var/log/myapp/server.log

💡 Drop in /usr/local/bin/ — never worry about disk space from logs again. Full version w/ self-tests in workspace.