← Back to all snippets
BASH

Monitor Disk Space and Send Email Alerts

Implement a critical server monitoring script that checks disk space usage and dispatches email alerts to administrators when thresholds are surpassed.

#!/bin/bash

# --- Configuration Start ---
THRESHOLD=85 # Percentage of disk usage that triggers an alert
EMAIL_RECIPIENT="[email protected]"
SERVER_NAME="$(hostname)"
DEVICE_TO_MONITOR="/dev/sda1" # Or mount point, e.g., '/' or '/var'
# --- Configuration End ---

# Check if mail command is available
if ! command -v mail &> /dev/null; then
    echo "Error: 'mail' command not found. Please install mailutils or similar." >&2
    exit 1
fi

# Get disk usage for the specified device/mount point
# df -h: Human-readable format
# awk: Extracts the percentage used (5th field) and removes '%' sign
# grep: Filters for the specific device/mount point
USED_PERCENTAGE=$(df -h "$DEVICE_TO_MONITOR" | awk 'NR==2 {print $5}' | sed 's/%//')

# Check if we got a valid number
if [[ -z "$USED_PERCENTAGE" || ! "$USED_PERCENTAGE" =~ ^[0-9]+$ ]]; then
    echo "Error: Could not determine disk usage for $DEVICE_TO_MONITOR." >&2
    exit 1
fi

# Compare with threshold
if (( USED_PERCENTAGE > THRESHOLD )); then
  SUBJECT="ALERT: High Disk Usage on $SERVER_NAME - $DEVICE_TO_MONITOR"
  BODY="Disk usage on $SERVER_NAME for $DEVICE_TO_MONITOR is currently at $USED_PERCENTAGE%, exceeding the threshold of $THRESHOLD%.

$(df -h)"

  echo "Sending email alert: $SUBJECT"
  echo -e "$BODY" | mail -s "$SUBJECT" "$EMAIL_RECIPIENT"
  if [ $? -eq 0 ]; then
    echo "Email alert sent successfully."
  else
    echo "Failed to send email alert." >&2
  fi
else
  echo "Disk usage for $DEVICE_TO_MONITOR is at $USED_PERCENTAGE%, which is below the threshold of $THRESHOLD%. No alert sent."
fi
How it works: This script is a crucial part of server monitoring. It checks the disk space utilization for a specified partition or mount point (`/dev/sda1` or `/`). Using `df -h` and `awk`, it extracts the current percentage of disk usage. If this percentage exceeds a predefined `THRESHOLD`, the script constructs an email alert containing the server name, disk details, and current usage, then sends it to the configured `EMAIL_RECIPIENT` using the `mail` command. This proactive monitoring helps prevent disk-full issues that can lead to service outages.

Need help integrating this into your project?

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

Hire DigitalCodeLabs