BASH

Automate Log File Archiving and Cleanup

Create a bash script to automatically archive and clean up old log files, helping manage disk space and keeping server logs organized.

#!/bin/bash

LOG_DIR="/var/log/nginx/" # Directory containing log files
ARCHIVE_DIR="/var/log/nginx/archive/"
DAYS_TO_KEEP=7 # Number of days to keep unarchived logs

mkdir -p $ARCHIVE_DIR

find $LOG_DIR -maxdepth 1 -type f -name "*.log" -mtime +$DAYS_TO_KEEP -print0 | while IFS= read -r -d $'\0' logfile; do
  if [ -f "$logfile" ]; then
    FILENAME=$(basename "$logfile")
    TIMESTAMP=$(date +%Y%m%d%H%M%S)
    echo "Archiving $logfile to ${ARCHIVE_DIR}${FILENAME}.${TIMESTAMP}.gz"
    gzip -c "$logfile" > "${ARCHIVE_DIR}${FILENAME}.${TIMESTAMP}.gz" && rm "$logfile"
  fi
done

# Optional: Clean up old archives (e.g., keep only 30 days of archives)
# find $ARCHIVE_DIR -type f -name "*.gz" -mtime +30 -delete

echo "Log archiving complete."
How it works: This script automates the process of archiving old log files. It scans a specified directory for `.log` files older than a set number of days, compresses them using `gzip`, moves them to an archive directory, and then deletes the original uncompressed logs. This helps manage disk space and keeps the primary log directory clean, making it ideal for regular execution via cron jobs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs