BASH

Check Disk Space and Send Alert if Above Threshold

A bash script to check disk space utilization on mounted file systems and send an alert email if usage exceeds a specified percentage threshold.

#!/bin/bash

THRESHOLD=85 # Percentage
ALERT_EMAIL="[email protected]"
HOSTNAME=$(hostname)

df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output; do
  usage=$(echo $output | awk '{ print $1 }' | sed 's/%//g')
  partition=$(echo $output | awk '{ print $2 }')

  if (( usage > THRESHOLD )); then
    MESSAGE="High disk space usage on $HOSTNAME: $partition is at $usage%."
    echo "$MESSAGE" | mail -s "Disk Space Alert on $HOSTNAME" "$ALERT_EMAIL"
    echo "Alert sent: $MESSAGE"
  else
    echo "Disk space on $partition is $usage%. OK."
  fi
done
How it works: This script uses the `df -h` command to list disk space usage in a human-readable format. It then filters out unwanted filesystems (like `tmpfs` or CD-ROMs) and processes each remaining line. For each partition, it extracts the usage percentage. If the usage exceeds the `THRESHOLD` defined at the top, it constructs an alert message and sends it via email using the `mail` command. This helps system administrators proactively prevent disk-full issues on web servers by providing timely notifications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs