BASH
Monitor Disk Space Usage and Send Email Alerts
Create a Bash script to periodically check your server's disk space. If usage exceeds a threshold, an email alert is sent, preventing critical storage issues on your web server.
#!/bin/bash
# Configuration
THRESHOLD=90 # Percentage of disk usage that triggers an alert
ALERT_EMAIL="[email protected]"
SERVER_NAME="My Web Server"
# Get disk usage for the root filesystem (or any mounted filesystem)
# -h: human-readable output
# -P: POSIX format (avoids issues with spaces in mount points)
# awk '{print $5}' selects the 5th column (percentage used)
# sed 's/%//g' removes the '%' sign
USED_PERCENTAGE=$(df -hP / | awk '{print $5}' | sed '1d' | sed 's/%//g')
# Check if mail command is available
if ! command -v mail &> /dev/null; then
echo "Error: 'mail' command not found. Please install mailutils (Debian/Ubuntu) or mailx (CentOS/RHEL)." >&2
exit 1
fi
if (( USED_PERCENTAGE > THRESHOLD )); then
SUBJECT="ALERT: High Disk Usage on ${SERVER_NAME} ( ${USED_PERCENTAGE}% )"
BODY="Disk space on ${SERVER_NAME} is at ${USED_PERCENTAGE}% used. Please take action to free up space.
Detailed usage:
$(df -hP /)"
echo -e "${BODY}" | mail -s "${SUBJECT}" "${ALERT_EMAIL}"
echo "Alert email sent for high disk usage: ${USED_PERCENTAGE}%"
else
echo "Disk usage is normal: ${USED_PERCENTAGE}%"
fi
How it works: This script monitors disk space usage on a server and sends an email alert if a predefined threshold is exceeded. It uses `df -hP` to get disk usage information, then `awk` and `sed` to extract the percentage of disk space used for the root filesystem. If this percentage is greater than the configured `THRESHOLD`, it constructs an email subject and body, including detailed disk usage output, and sends it to the specified `ALERT_EMAIL` using the `mail` command. This is crucial for preventing unexpected outages due to full disks.