BASH

Monitor Disk Space and Send Email Alerts in Bash

Keep your web servers healthy by monitoring disk usage with a bash script that sends email notifications when space falls below a critical threshold.

#!/bin/bash

THRESHOLD=90 # Percentage
ADMIN_EMAIL="[email protected]"
PARTITION="/"

USAGE=$(df -h "$PARTITION" | awk 'NR==2 {print $5}' | sed 's/%//g')

if (( USAGE > THRESHOLD )); then
  echo "Warning: Disk usage on $PARTITION is at $USAGE%, which is above the threshold of $THRESHOLD%."
  echo "Sending email alert to $ADMIN_EMAIL..."
  echo "Disk usage on $PARTITION is at $USAGE%. Please check the server." | mail -s "High Disk Usage Alert on $(hostname)" "$ADMIN_EMAIL"
else
  echo "Disk usage on $PARTITION is at $USAGE%. All good."
fi
How it works: This script checks the disk usage for a specified partition and sends an email alert if it exceeds a predefined threshold. It uses `df -h` to get human-readable disk space information, `awk` and `sed` to extract the percentage usage, and then compares it against the `THRESHOLD`. If the usage is too high, it sends an email using the `mail` command. Ensure `mailutils` or a similar package is installed for the `mail` command to work. Customize `THRESHOLD`, `ADMIN_EMAIL`, and `PARTITION` variables as needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs