Overview
This script monitors disk usage across all mounted filesystems and sends email alerts when usage exceeds a configurable threshold. Ideal for cron job automation.
The Script
#!/bin/bash
# Disk Space Alert Script
# Usage: ./disk-alert.sh [threshold] [email]
THRESHOLD=\${1:-85}
EMAIL=\${2:-"[email protected]"}
HOSTNAME=$(hostname)
DATE=$(date '+%Y-%m-%d %H:%M:%S')
# Get disk usage, skip header and tmpfs
df -h | awk 'NR>1 && !/tmpfs/ {print $5, $6}' | while read usage mount; do
# Remove % sign and compare
usage_int=\${usage%\%}
if [ "$usage_int" -ge "$THRESHOLD" ]; then
echo "WARNING: $mount is \${usage} full on $HOSTNAME at $DATE" | \\
mail -s "Disk Alert: $HOSTNAME - $mount at \${usage}" "$EMAIL"
# Also log locally
logger -t disk-alert "WARNING: $mount is \${usage} full"
fi
done
echo "Disk check completed at $DATE"Installation
- Save the script:
sudo vim /usr/local/bin/disk-alert.sh
sudo chmod +x /usr/local/bin/disk-alert.sh- Add to crontab (check every hour):
# Edit root's crontab
sudo crontab -e
# Add this line (runs every hour)
0 * * * * /usr/local/bin/disk-alert.sh 85 [email protected]Configuration Options
| Parameter | Default | Description |
|---|---|---|
| threshold | 85 | Percentage at which to alert |
| [email protected] | Email recipient for alerts |
Requirements
- `mailutils` or `mailx` for email sending
- Proper mail configuration (postfix, sendmail, etc.)
- disk space
- monitoring
- alert
- threshold
- df
- cron