BASH
Simple Web Server Log File Archiving
Automate the archiving and compression of old web server access logs to save disk space and keep your log directories organized for easier analysis.
#!/bin/bash
LOG_DIR="/var/log/nginx"
ARCHIVE_DIR="/var/log/nginx/archive"
if [ ! -d "$ARCHIVE_DIR" ]; then
mkdir -p "$ARCHIVE_DIR"
fi
find "$LOG_DIR" -maxdepth 1 -type f -name "*.log" -mtime +7 -print0 | while IFS= read -r -d $'\0' file; do
FILENAME=$(basename "$file")
TIMESTAMP=$(date +%Y%m%d%H%M%S)
echo "Archiving and compressing $file..."
gzip "$file" && mv "${file}.gz" "$ARCHIVE_DIR/${FILENAME%.log}_${TIMESTAMP}.gz"
done
echo "Log archiving complete."
How it works: This script automates log file management. It searches a specified `LOG_DIR` for `.log` files older than 7 days. For each old log file found, it compresses it using `gzip` and then moves the compressed file to an `ARCHIVE_DIR`, appending a timestamp to the filename for unique identification and better organization.