Custom Log Rotation Shell Script for Linux (/var/log Cleanup)

log rotation shell script linux

Supplement or replace default logrotate with a custom log rotation script for full control over compression and retention.

What this script does

  • Rotates logs matching configurable patterns
  • Compresses rotated files with gzip
  • Deletes logs older than retention period
  • Supports multiple directories
  • Logs all rotation actions

Prerequisites

  • Root access to /var/log
  • gzip installed

Step 1: Save the script

sudo nano /usr/local/bin/log-rotate-custom.sh
sudo chmod +x /usr/local/bin/log-rotate-custom.sh

Step 2: Full script (scroll to read)

log-rotate-custom.sh
#!/usr/bin/env bash
set -euo pipefail

LOG_DIRS=("/var/log/nginx" "/var/log/apache2")
PATTERN="*.log"
KEEP_DAYS=14
MAX_SIZE_MB=100
LOG="/var/log/log-rotate-custom.log"

log(){ echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

rotate_file(){
  local f="$1"
  local size_mb
  size_mb=$(du -m "$f" | awk '{print $1}')
  if (( size_mb >= MAX_SIZE_MB )); then
    local dest="${f}.$(date +%F).1"
    cp "$f" "$dest"
    : > "$f"
    gzip -f "$dest"
    log "Rotated: $f -> ${dest}.gz"
  fi
}

for dir in "${LOG_DIRS[@]}"; do
  [[ -d "$dir" ]] || continue
  find "$dir" -maxdepth 1 -name "$PATTERN" -type f | while read -r f; do
    rotate_file "$f"
  done
  find "$dir" -name "*.gz" -mtime +"$KEEP_DAYS" -delete
  log "Cleaned logs older than ${KEEP_DAYS}d in $dir"
done
log "Log rotation completed"

Scroll inside the box to read the full script.

Step 3: Configure settings

  • LOG_DIRS — directories to scan
  • PATTERN — file pattern e.g. *.log
  • KEEP_DAYS — retention in days
Custom log rotation shell script on Linux server
Custom log rotation shell script on Linux server

Step 4: Test manually

sudo /usr/local/bin/log-rotate-custom.sh
ls -lah /var/log/nginx/

Schedule with cron

sudo crontab -e

Add:

0 0 * * * /usr/local/bin/log-rotate-custom.sh >> /var/log/log-rotate-custom.log 2>&1

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).