You can use a safe interactive log cleanup script that:
Scans
/var/logfor the largest files.Shows their sizes.
Asks for confirmation before clearing each file.
Clears only files you approve.
Keeps the log files in place, so services can continue writing to them.
Script: cleanup_logs.sh
###################################################
#!/bin/bash
LOG_DIR="/var/log"MIN_SIZE="+100M"
if [[ $EUID -ne 0 ]]; then echo "Please run this script as root." exit 1fi
echo "========== Disk Usage Before =========="df -h "$LOG_DIR"du -sh "$LOG_DIR"
echoecho "Scanning log files larger than 100 MB..."echo
find "$LOG_DIR" -type f -size "$MIN_SIZE" -print0 |while IFS= read -r -d '' file; do
# Skip symlinks [[ -L "$file" ]] && continue
size=$(du -h "$file" | cut -f1)
echo "--------------------------------------" echo "File : $file" echo "Size : $size"
read -r -p "Clear this file? (yes/no): " answer </dev/tty
if [[ "$answer" == "yes" ]]; then if truncate -s 0 -- "$file"; then echo "CLEARED: $file" else echo "FAILED: $file" fi else echo "SKIPPED: $file" fidone
echoecho "========== Disk Usage After =========="df -h "$LOG_DIR"du -sh "$LOG_DIR"
echo "Cleanup completed."
#######################################
How to run
Save the script:
vi /root/cleanup_logs.sh
Make it executable:
chmod +x /root/cleanup_logs.sh
Run:
/root/cleanup_logs.sh
Example output
========== Disk Usage Before ==========
45G /var/log
Scanning log files larger than 100 MB...
--------------------------------------
File : /var/log/messages
Size : 28G
Clear this file? (yes/no): yes
CLEARED: /var/log/messages
--------------------------------------
File : /var/log/secure
Size : 9G
Clear this file? (yes/no): no
SKIPPED: /var/log/secure
--------------------------------------
File : /var/log/httpd/access_log
Size : 850M
Clear this file? (yes/no): no
SKIPPED: /var/log/httpd/access_log
========== Disk Usage After ==========
17G /var/log
Cleanup completed.
Important safety precautions
The script clears file contents permanently, not just old log entries. In particular, audit logs, security logs, and application logs may be needed for troubleshooting, retention requirements, or investigations.
For production servers, I recommend reviewing files first and using logrotate or journalctl --vacuum-size for managed logs where appropriate. This script requires typing the full word yes for every file; anything else skips it.
Comments
Post a Comment