BASH
Monitor Disk Usage and Alert on High Consumption
Regularly check disk space usage on specified partitions and send an email alert if consumption exceeds a predefined threshold.
#!/bin/bash
# Configuration
THRESHOLD=90 # Percentage threshold for disk usage
PARTITION="/" # The disk partition to monitor (e.g., '/', '/var', '/home')
ALERT_EMAIL="[email protected]" # Email address to send alerts
HOST_NAME=$(hostname)
# Check if 'mail' command is available
if ! command -v mail &> /dev/null
then
echo "'mail' command not found. Please install mailutils (e.g., sudo apt install mailutils)."
exit 1
fi
# Get current disk usage percentage for the specified partition
USAGE=$(df -h "$PARTITION" | awk 'NR==2 {print $5}' | sed 's/%//')
echo "Checking disk usage for $PARTITION on $HOST_NAME... Current usage: $USAGE%"
# Compare usage with threshold
if (( USAGE > THRESHOLD )); then
SUBJECT="Disk Space Alert on $HOST_NAME - $PARTITION at $USAGE%"
BODY="Disk usage on $HOST_NAME for partition $PARTITION has exceeded the threshold of $THRESHOLD%. Current usage: $USAGE%."
echo "$BODY"
echo "Sending alert email to $ALERT_EMAIL..."
# Send email
echo "$BODY" | mail -s "$SUBJECT" "$ALERT_EMAIL"
if [ $? -eq 0 ]; then
echo "Alert email sent successfully."
else
echo "Failed to send alert email. Check mail configuration."
fi
else
echo "Disk usage is within acceptable limits."
fi
How it works: This script monitors the disk usage of a specified partition and sends an email alert if the usage exceeds a configurable threshold. It uses `df -h` to get human-readable disk space information, then `awk` and `sed` to extract the percentage of used space. If this percentage is above the `THRESHOLD`, it constructs an email with relevant details and sends it using the `mail` command (which requires a configured MTA like Postfix or Sendmail). This is crucial for web developers to prevent servers from running out of disk space, which can lead to application failures or data corruption.