Disk Usage Alert System

Monitors disk usage and sends email or notification when threshold is exceeded. Critical monitoring tool for system administrators.

Published: February 10, 2024 Updated: November 25, 2024

Detailed Information

This script continuously monitors disk usage on your system and alerts you when the specified threshold is exceeded. Since disk fullness can cause system crashes and data loss, it is a critical monitoring tool.

What Does This Script Do?

This script checks all mounted disk partitions and calculates usage percentage. When threshold is exceeded:

  • Sends email alert
  • Lists largest directories (shows which directories are using disk space)
  • Provides detailed report

Why Should You Use It?

Disk fullness can cause serious problems in Linux systems:

  • System crashes
  • Data loss risk
  • Application errors
  • Inability to write log files
  • Database operations stopping

With this script, you can detect problems early and take preventive measures.

Features

  • Automatic disk usage monitoring
  • Email notifications
  • Listing of largest directories
  • Customizable threshold value
  • Full automation with cron job

How to Use

Step-by-Step Usage Guide

1. Email Setup

Install mail tool to send emails:

# Ubuntu/Debian
sudo apt-get install mailutils

# CentOS/RHEL
sudo yum install mailx

2. Create Script File

nano disk_alert.sh

Paste the script code and save.

3. Configuration Settings

Edit variables at the beginning of the script:

THRESHOLD=80              # Alert threshold (percentage)
EMAIL="[email protected]"  # Email to send notifications

4. Make Script Executable

chmod +x disk_alert.sh

5. Test Run

./disk_alert.sh

6. Automate with Cron Job

# Edit crontab
crontab -e

# Run every hour
0 * * * * /path/to/disk_alert.sh >> /var/log/disk_alert.log 2>&1

# Run every 30 minutes
*/30 * * * * /path/to/disk_alert.sh >> /var/log/disk_alert.log 2>&1

Threshold Value Settings

You can use different threshold values for different disks. Edit the script to set lower threshold values for critical disks.

Requirements

Requirements

  • Linux/Unix System: Script works on Linux and Unix-based systems
  • df command: For disk usage information (installed by default)
  • du command: For directory sizes (installed by default)
  • mail/mailx: For sending emails
  • awk, grep, sort: For data processing (installed by default)

Email Setup

You need to install mail tool to send emails:

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install mailutils

# CentOS/RHEL
sudo yum install mailx

# Email configuration (optional)
sudo dpkg-reconfigure mailutils  # Debian/Ubuntu

SMTP Configuration

You may need to configure SMTP server information to send emails. You can use Gmail, SendGrid, or your own SMTP server.

Use Cases

Use Cases

1. Production Server Monitoring

Continuously monitor disk usage on your production servers. Get instant notification when critical threshold is reached.

2. Log File Management

Monitor disk usage to prevent log files from filling disk space and perform log rotation if necessary.

3. Backup Space Control

Monitor disk usage to prevent backup directories from filling up and clean old backups.

4. Multi-Server Monitoring

If you have multiple servers, you can create a centralized monitoring system by running this script on each one.

5. Proactive Problem Solving

You can detect and solve disk fullness problems before they occur.

6. SLA Compliance

If service level agreements require disk usage monitoring, you can ensure compliance with this script.

Examples

Usage Examples

Example 1: Basic Usage

# Run script
./disk_alert.sh

# Output:
# Checking disk usage on server1...
# 
# Partition: /dev/sda1
# Mount Point: /
# Usage: 85%
# ⚠️  WARNING: Disk usage is above threshold!
# 
# Top 10 largest directories in /:
# 15G    /var/log
# 10G    /home/user
# 5G     /tmp

Example 2: Different Threshold Values

# Low threshold for critical disks
THRESHOLD=70  # For / (root)
THRESHOLD=90  # For /home

# You can use different thresholds by editing the script

Example 3: Slack/Telegram Notification

# Use webhook instead of email
send_alert() {
    local partition=$1
    local usage=$2
    curl -X POST -H 'Content-Type: application/json' \
        -d "{\"text\":\"Disk usage on $partition: ${usage}%\"}" \
        https://hooks.slack.com/services/YOUR/WEBHOOK/URL
}

Example 4: Automatic Cleanup

# Automatic cleanup when threshold exceeded
if [ $USAGE -ge $THRESHOLD ]; then
    # Clean old log files
    find /var/log -name "*.log" -mtime +30 -delete
    # Clean temp files
    rm -rf /tmp/*
fi

Code

#!/bin/bash

# Disk Usage Alert System

THRESHOLD=80
EMAIL="[email protected]"
HOSTNAME=$(hostname)

echo "Checking disk usage on $HOSTNAME..."
echo ""

send_alert() {
    local partition=$1
    local usage=$2
    local subject="ALERT: Disk Usage on $HOSTNAME"
    local message="WARNING: Disk usage on $partition has reached ${usage}%\n\nPlease investigate immediately."
    
    echo -e "$message" | mail -s "$subject" "$EMAIL"
}

df -H | grep -vE "^Filesystem|tmpfs|cdrom|loop" | awk "{ print \$5 \" \" \$1 \" \" \$6 }" | while read output; do
    USAGE=$(echo $output | awk "{ print \$1}" | cut -d"%" -f1)
    PARTITION=$(echo $output | awk "{ print \$2 }")
    MOUNT=$(echo $output | awk "{ print \$3 }")
    
    echo "Partition: $PARTITION"
    echo "Mount Point: $MOUNT"
    echo "Usage: $USAGE%"
    
    if [ $USAGE -ge $THRESHOLD ]; then
        echo "⚠️  WARNING: Disk usage is above threshold!"
        send_alert "$PARTITION ($MOUNT)" "$USAGE"
        
        echo ""
        echo "Top 10 largest directories in $MOUNT:"
        du -h "$MOUNT" 2>/dev/null | sort -rh | head -n 10
    else
        echo "✓ Status: OK"
    fi
    echo ""
    echo "---"
    echo ""
done

echo "Disk usage check completed at $(date)"

Usage

# Configure email
sudo apt-get install mailutils  # Debian/Ubuntu
# or
sudo yum install mailx  # CentOS/RHEL

# Edit script
nano disk_alert.sh
# Replace EMAIL with your email

chmod +x disk_alert.sh

# Manual test
./disk_alert.sh

# Automate with crontab (every hour)
crontab -e
# Add: 0 * * * * /path/to/disk_alert.sh

Troubleshooting

Troubleshooting

Problem: Email Not Sending

Solution: Make sure mail tool is installed and SMTP configuration is correct:

# Test mail tool
echo "Test" | mail -s "Test" [email protected]

# Check SMTP configuration
cat /etc/postfix/main.cf  # If using Postfix

Problem: "df: command not found"

Solution: df command is usually installed by default. If missing:

# Ubuntu/Debian
sudo apt-get install coreutils

# CentOS/RHEL
sudo yum install coreutils

Problem: Incorrect Disk Usage Percentage

Solution: Check the output format of df command. Format may differ on some systems. Edit the script according to your system.

Problem: Script Running Too Frequently

Solution: Check cron job settings. Running every hour may be sufficient. Running too frequently sends unnecessary emails.

Problem: Email Going to Spam

Solution: Make email subject and content more descriptive. Check SPF, DKIM records.

Tags

disk monitoring alert system disk usage notification