#!/bin/bash # Configuration LOG_DIR="/var/log/nginx" # Directory containing log files RETENTION_DAYS=7 # Number of days to keep logs # --- Log Rotation --- # This example moves current .log files to a dated format and then gzipps them. # For more robust solutions, consider logrotate utility. echo "Starting log rotation and cleanup for $LOG_DIR at $(date)" # 1. Move current active logs to a dated name (e.g., access.log -> access.log.YYYYMMDD) # Only do this if the dated log for today doesn't already exist to avoid double processing. for log_file in "$LOG_DIR"/*.log; do if [ -f "$log_file" ]; then base_name=$(basename "$log_file" .log) dated_log_file="$LOG_DIR/${base_name}.log.$(date +%Y%m%d)" if [ ! -f "$dated_log_file" ] && [ ! -f "${dated_log_file}.gz" ]; then mv "$log_file" "$dated_log_file" echo "Moved $log_file to $dated_log_file" fi fi done # 2. Gzip logs that were dated today and are not yet gzipped find "$LOG_DIR" -maxdepth 1 -type f -name "*.log.$(date +%Y%m%d)" ! -name "*.gz" -exec gzip {} \; # --- Log Cleanup --- # Delete all gzipped logs older than RETENTION_DAYS echo "Deleting logs older than $RETENTION_DAYS days from $LOG_DIR" find "$LOG_DIR" -type f -name "*.log.*.gz" -mtime +"$RETENTION_DAYS" -delete echo "Log cleanup complete for $LOG_DIR at $(date)"