BASH

Monitoring and Cleaning Up Disk Space on Servers

A practical Bash script to check disk usage, identify large files or directories, and automate cleanup of old log files on a server.

#!/bin/bash

# --- Configuration ---
# Threshold for disk usage percentage (e.g., 80 for 80%)
DISK_USAGE_THRESHOLD=80
# Directory to check for old log files to clean
LOG_DIR="/var/log/nginx"
# Files older than N days to delete (e.g., 30 days)
DAYS_TO_KEEP=30

# --- Functions ---
check_disk_usage() {
    echo "--- Disk Usage Report ---"
    df -h / | grep / | awk '{print "Filesystem: " $1 ", Used: " $5 ", Mounted on: " $6}'
    
    # Get current disk usage percentage for root partition
    USAGE=$(df / | grep / | awk '{print $5}' | sed 's/%//g')
    
    if (( USAGE > DISK_USAGE_THRESHOLD )); then
        echo "WARNING: Disk usage is at $USAGE%, which is above the threshold of $DISK_USAGE_THRESHOLD%!"
        echo "Identifying large directories in /var/log/..."
        du -sh /var/log/* | sort -rh | head -n 10
        echo "Identifying large directories in /var/www/..."
        du -sh /var/www/* | sort -rh | head -n 10
    else
        echo "Disk usage is currently at $USAGE%, which is within the acceptable range."
    fi
    echo
}

clean_old_logs() {
    if [ ! -d "$LOG_DIR" ]; then
        echo "Warning: Log directory '$LOG_DIR' does not exist. Skipping log cleanup."
        return
    fi
    
    echo "--- Cleaning Old Logs in $LOG_DIR ---"
    echo "Finding log files older than $DAYS_TO_KEEP days..."
    
    # Find and list files older than DAYS_TO_KEEP
    find "$LOG_DIR" -type f -name "*.log" -mtime +$DAYS_TO_KEEP -print
    
    read -p "Delete these files? (y/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]
then
        find "$LOG_DIR" -type f -name "*.log" -mtime +$DAYS_TO_KEEP -delete
        echo "Old log files deleted."
    else
        echo "Log cleanup cancelled."
    fi
    echo
}

# --- Main Execution ---
check_disk_usage
clean_old_logs

echo "Disk maintenance script finished."
How it works: This script helps web developers monitor server disk space and perform basic cleanup. It reports the current disk usage, warns if a threshold is exceeded, and identifies large directories using `df` and `du`. Additionally, it can automatically find and delete old log files in a specified directory using `find`, helping maintain server health.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs