BASH
Automate Log File Cleanup by Age
Learn to create a bash script for automatically cleaning up old log files from a specified directory, preventing disk space exhaustion and maintaining server health.
#!/bin/bash
# Configuration
LOG_DIR="/var/log/apache2" # Directory containing log files
RETENTION_DAYS=7 # Number of days to keep log files
# Check if log directory exists
if [ ! -d "$LOG_DIR" ]; then
echo "Error: Log directory '$LOG_DIR' not found."
exit 1
fi
echo "Starting log cleanup in $LOG_DIR (keeping files from last $RETENTION_DAYS days)..."
# Find and delete files older than RETENTION_DAYS
find "$LOG_DIR" -type f -name "*.log" -mtime +$RETENTION_DAYS -print -delete
if [ $? -eq 0 ]; then
echo "Log cleanup completed successfully."
else
echo "Log cleanup encountered errors."
fi
How it works: This script automates the deletion of old log files. It's configured with a 'LOG_DIR' and 'RETENTION_DAYS'. It first validates the directory, then uses 'find' to locate files ending with '.log' that were modified more than 'RETENTION_DAYS' ago, printing their names before deleting them. This helps prevent disk space issues on web servers.