BASH
Monitor Server Disk Usage and Alert
Keep an eye on your server's disk space. This Bash script checks partitions' usage and triggers an alert if any exceed a predefined threshold.
#!/bin/bash
THRESHOLD=80 # Percentage
ALERT_EMAIL="[email protected]" # Email for alerts (requires mail command setup)
# Get disk usage for all mounted filesystems, exclude snap, squashfs, tmpfs, devtmpfs, etc.
DISK_USAGE=$(df -h --output=source,pcent,target | grep -vE '^Filesystem|snap|squashfs|tmpfs|devtmpfs|cdrom|loop')
HIGH_USAGE_PARTITIONS=""
while IFS= read -r line; do
PARTITION=$(echo "$line" | awk '{print $1}')
USAGE_PERCENT=$(echo "$line" | awk '{print $2}' | sed 's/%//')
MOUNT_POINT=$(echo "$line" | awk '{print $3}')
if (( USAGE_PERCENT > THRESHOLD )); then
HIGH_USAGE_PARTITIONS+="Partition: $PARTITION ($MOUNT_POINT) is at ${USAGE_PERCENT}% usage.
"
fi
done <<< "$DISK_USAGE"
if [ -n "$HIGH_USAGE_PARTITIONS" ]; then
SUBJECT="CRITICAL: High Disk Usage on $(hostname)"
MESSAGE="The following partitions are exceeding the ${THRESHOLD}% usage threshold:
${HIGH_USAGE_PARTITIONS}
Please take action to free up space."
echo -e "$MESSAGE" # Print to console
# echo -e "$MESSAGE" | mail -s "$SUBJECT" "$ALERT_EMAIL" # Uncomment to send email
echo "Alert triggered for high disk usage."
else
echo "All disk partitions are within acceptable limits."
fi
How it works: This script monitors the disk usage of all mounted filesystems on a server. It iterates through each partition, checks its usage percentage, and compares it against a defined `THRESHOLD`. If any partition's usage exceeds this threshold, it compiles an alert message. The script prints the alert to the console and includes a commented-out line to send an email notification, which requires a `mail` command setup.