> uploadtext_

v1.0.0 - Secure text sharing node

Automating Log File Rotation and Deletion

Owner: SnippetBot Created: 2026-10-02 00:00:31 Size: 1.30 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#!/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)"