← Back to all snippets
BASH

Monitor Disk Usage and Send Email Alerts

Set up a bash script to monitor disk space on critical partitions, sending an email alert when usage exceeds a defined threshold, ensuring proactive system maintenance.

#!/bin/bash

# --- Configuration ---
THRESHOLD=90                       # Percentage threshold for disk usage
EMAIL_RECIPIENT="[email protected]" # Email address to send alerts
PARTITION="/"                      # Partition to monitor (e.g., /, /var, /home)
ALERT_SUBJECT="Disk Usage Alert on $(hostname)"

# --- Check for mail command ---
if ! command -v mail &> /dev/null; then
    echo "Error: 'mail' command not found. Please install mailutils or equivalent."
    echo "On Debian/Ubuntu: sudo apt install mailutils"
    echo "On CentOS/RHEL: sudo yum install mailx"
    exit 1
fi

# --- Get current disk usage ---
# Use 'df -h' for human-readable output
# 'awk' to extract the percentage for the specified partition
# 'sed' to remove the '%' sign
USAGE=$(df -h "$PARTITION" | awk 'NR==2 {print $5}' | sed 's/%//g')

# --- Check if USAGE is a valid number ---
if ! [[ "$USAGE" =~ ^[0-9]+$ ]]; then
    echo "Error: Could not determine disk usage for partition '$PARTITION'. Raw output: $(df -h "$PARTITION")"
    exit 1
fi

echo "Current disk usage for $PARTITION: ${USAGE}%"

# --- Compare with threshold and send alert if necessary ---
if (( USAGE > THRESHOLD )); then
  ALERT_BODY="Disk usage on $(hostname) for partition '$PARTITION' is at ${USAGE}%, which exceeds the threshold of ${THRESHOLD}%.

"
  ALERT_BODY+="Please investigate disk space usage.
"
  ALERT_BODY+="Current disk usage details:

$(df -h "$PARTITION")"
  
  echo -e "$ALERT_BODY" | mail -s "$ALERT_SUBJECT" "$EMAIL_RECIPIENT"
  
  if [ $? -eq 0 ]; then
    echo "Alert email sent to $EMAIL_RECIPIENT."
  else
    echo "Failed to send alert email."
  fi
else
  echo "Disk usage for $PARTITION is within the acceptable limits (${USAGE}% <= ${THRESHOLD}%)."
fi

echo "Script finished."
How it works: This script monitors disk usage for a specified `PARTITION` and sends email alerts if it exceeds a `THRESHOLD`. It first checks for the `mail` command. It then uses `df -h` and `awk` to extract the numerical disk usage percentage for the target partition. After validating the retrieved usage, it compares it against the defined threshold. If the usage is higher, an informative email containing current disk usage details is composed and sent to the `EMAIL_RECIPIENT` using the `mail` command.

Need help integrating this into your project?

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

Hire DigitalCodeLabs