#!/bin/bash LOG_DIR="/var/log/myapp/" MAX_AGE_DAYS=7 # Logs older than this will be rotated ARCHIVE_DIR="/var/log/myapp/archive/" # Create archive directory if it doesn't exist mkdir -p "$ARCHIVE_DIR" # Find log files older than MAX_AGE_DAYS and move them to archive # Using -name '*.log' to target specific log files # -mtime +N: file's data was last modified N*24 hours ago. +N means more than N days. find "$LOG_DIR" -maxdepth 1 -type f -name '*.log' -mtime +"$MAX_AGE_DAYS" -print0 | while IFS= read -r -d $'\0' logfile; do # Generate a timestamp for the archived file TIMESTAMP=$(date +%Y%m%d%H%M%S) FILENAME=$(basename "$logfile") ARCHIVED_NAME="${ARCHIVE_DIR}${FILENAME}.${TIMESTAMP}.gz" echo "Archiving and compressing $logfile to $ARCHIVED_NAME" gzip < "$logfile" > "$ARCHIVED_NAME" && rm "$logfile" if [ $? -ne 0 ]; then echo "Error archiving $logfile" fi done # Optional: Delete archives older than a certain period (e.g., 30 days) # find "$ARCHIVE_DIR" -type f -name '*.gz' -mtime +30 -delete echo "Log rotation complete."