BASH
Monitor Disk Space Usage and Alert
Monitor server disk space, identifying partitions nearing capacity and sending an alert if usage exceeds a predefined threshold, crucial for web server health.
#!/bin/bash
THRESHOLD=90 # Percentage
EMAIL="[email protected]"
echo "Checking disk space usage on $(hostname)..."
# Get disk usage for all mounted filesystems, excluding temporary/virtual ones
# --output=pcent,target: output usage percentage and mount point
# grep -v 'Use%|tmpfs|udev|/dev/loop': filter out headers and unwanted filesystems
# sed 's/%//': remove percentage sign for numerical comparison
DF_OUTPUT=$(df -h --output=pcent,target | grep -v 'Use%\|tmpfs\|udev\|/dev/loop' | sed 's/%//')
# Loop through each line of the df output
while IFS= read -r line; do
USAGE=$(echo $line | awk '{print $1}')
PARTITION=$(echo $line | awk '{print $2}')
# Compare usage with threshold
if (( USAGE > THRESHOLD )); then
MESSAGE="Alert: Disk usage on $PARTITION is at ${USAGE}% which is above the ${THRESHOLD}% threshold on $(hostname)."
echo "$MESSAGE" | mail -s "Disk Space Alert on $(hostname)" "$EMAIL"
echo "$MESSAGE"
else
echo "Disk usage on $PARTITION is ${USAGE}%. All good."
fi
done <<< "$DF_OUTPUT"
echo "Disk space check completed."
How it works: This script monitors disk space usage on the server. It retrieves the usage percentage for all mounted filesystems and compares it against a defined `THRESHOLD`. If any partition's usage exceeds this threshold, an email alert is sent to the specified administrator, providing a proactive warning to prevent potential service disruptions due to full disks, which can halt web services.