BASH
Monitor Disk Usage and Send Email Alert
Bash script to check server disk space usage and send an email alert if a specified threshold is exceeded, preventing critical storage issues.
#!/bin/bash
THRESHOLD=90 # Percentage
EMAIL_RECIPIENT="[email protected]"
SERVER_NAME=$(hostname)
# Get disk usage percentage for root partition
USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
if (( USAGE > THRESHOLD )); then
SUBJECT="Disk Space Alert on $SERVER_NAME"
BODY="Disk space usage on $SERVER_NAME is at $USAGE%, which exceeds the threshold of $THRESHOLD%.
Please take action to free up space."
echo -e "$BODY" | mail -s "$SUBJECT" "$EMAIL_RECIPIENT"
echo "Disk space alert sent to $EMAIL_RECIPIENT."
else
echo "Disk space usage is currently $USAGE%, below the threshold of $THRESHOLD%."
fi
How it works: This script monitors the disk space usage of the root partition. If the usage exceeds a predefined percentage threshold, it sends an email alert to a specified recipient. This proactive monitoring helps web developers prevent server outages caused by full disk space, ensuring system stability and performance. It relies on the `mail` command being configured on the server.