BASH

Monitor Disk Space and Send Email Alert

Proactively monitor server disk usage with a Bash script. It checks partitions and sends an email alert if usage exceeds a defined threshold, preventing downtime.

#!/bin/bash
# Configuration
THRESHOLD=85 # Percentage usage to trigger alert
ALERT_EMAIL="[email protected]"
HOSTNAME=$(hostname)

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

# Get disk usage for all mounted filesystems, exclude tempfs, cdrom, etc.
DF_OUTPUT=$(df -h | grep -vE "^tmpfs|udev|cdrom|loop|snap" | awk 'NR>1 {print $5 " " $1}')

ALERT_TRIGGERED=0
ALERT_MESSAGE="Disk Usage Alert for $HOSTNAME:

"

while IFS= read -r line; do
    USAGE=$(echo "$line" | awk '{print $1}' | sed 's/%//g')
    FILESYSTEM=$(echo "$line" | awk '{print $2}')

    if (( USAGE > THRESHOLD )); then
        ALERT_TRIGGERED=1
        ALERT_MESSAGE+="Filesystem: $FILESYSTEM is at ${USAGE}% usage (threshold: ${THRESHOLD}%)
"
        echo "ALERT: $FILESYSTEM is at ${USAGE}% usage!"
    else
        echo "$FILESYSTEM is at ${USAGE}% usage (OK)."
    fi
done <<< "$DF_OUTPUT"

if [ "$ALERT_TRIGGERED" -eq 1 ]; then
    echo -e "$ALERT_MESSAGE" | mail -s "Disk Space Alert - $HOSTNAME" "$ALERT_EMAIL"
    echo "Email alert sent to $ALERT_EMAIL."
else
    echo "All filesystems are below the threshold."
fi

echo "Disk monitoring script finished."
How it works: This script monitors the disk space usage on your server. It uses `df -h` to get disk usage, filters out irrelevant filesystems, and then iterates through the remaining ones. If any filesystem's usage exceeds the `THRESHOLD` percentage, it sends an email alert to the specified `ALERT_EMAIL` with details about the over-limit partitions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs