During long-term use of Linux, a large amount of unnecessary logs may accumulate. This can be fatal for VPS with limited storage, as when the logs fill up the hard drive, various services on the server will fail to start normally. This is a log cleanup script I wrote that can clean up useless logs.
#!/bin/bash
# Define log directory and size limit
LOG_DIR="/var/log"
SIZE_LIMIT="20M"
# Function: Delete all compressed log files
delete_compressed_logs() {
echo "Deleting all compressed log files..."
find "$LOG_DIR" -type f \( -name "*.gz" -o -name "*.xz" -o -name "*.zip" \) -exec rm -f {} \;
}
# Function: Delete log files larger than 20MB
delete_large_logs() {
echo "Deleting log files larger than $SIZE_LIMIT..."
find "$LOG_DIR" -type f -name "*.log" -size +"$SIZE_LIMIT" -exec rm -f {} \;
}
# Function: Truncate critical log files
truncate_critical_logs() {
echo "Truncating critical log files..."
> "$LOG_DIR/wtmp"
> "$LOG_DIR/btmp"
> "$LOG_DIR/lastlog"
}
# Function: Clean journal logs
clean_journal() {
echo "Cleaning journal logs..."
# journalctl --vacuum-time=7d
# Or clean by size limit
journalctl --vacuum-size=100M
}
# Function: Display disk usage and show capacity information in yellow
report_disk_usage() {
echo -e "\nCurrent disk usage:"
du -sh "$LOG_DIR" | awk '{print "\033[33m" $1 "\033[0m", $2}'
}
# Execute cleanup operations
report_disk_usage
delete_compressed_logs
delete_large_logs
truncate_critical_logs
clean_journal
report_disk_usage
echo "Log cleanup completed."