BASH
Archive and Clean Up Old Log Files
Implement a Bash script to manage server log files by archiving old logs, compressing them, and deleting original files to save disk space.
#!/bin/bash
# Configuration
LOG_DIR="/var/log/nginx"
ARCHIVE_DIR="/var/log/nginx/archive"
DAYS_OLD=7 # Files older than this many days will be archived
mkdir -p "${ARCHIVE_DIR}"
find "${LOG_DIR}" -maxdepth 1 -type f -name "*.log" -mtime +"${DAYS_OLD}" -print0 | while IFS= read -r -d $'\0' file
do
echo "Archiving and compressing ${file}..."
gzip -c "${file}" > "${ARCHIVE_DIR}/$(basename "${file}").$(date +"%Y%m%d").gz" || { echo "Failed to compress ${file}"; continue; }
rm "${file}" || { echo "Failed to remove original ${file}"; continue; }
echo "${file} archived and removed."
done
# Optional: Clean up archives older than, say, 30 days
# find "${ARCHIVE_DIR}" -type f -name "*.gz" -mtime +30 -delete
echo "Log cleanup completed."
How it works: This script automates the management of log files. It identifies log files within a specified directory that are older than `DAYS_OLD`, compresses them using `gzip`, moves the compressed archives to a separate archive directory, and then deletes the original, uncompressed log files. This helps in saving disk space and organizing logs, ensuring server performance and preventing disk overload.