BASH

Monitor Disk Space Usage with Threshold Alert

Script to monitor server disk space, alerting web developers when usage exceeds a defined percentage to prevent critical storage issues.

#!/bin/bash

# Configuration
THRESHOLD=85 # Percentage (e.g., 85 for 85%)
CHECK_PATH="/"
EMAIL_RECIPIENT="[email protected]"
EMAIL_SUBJECT="CRITICAL: Disk Space Alert on $(hostname)"

# Function to send email (requires 'mail' command or similar setup)
send_alert_email() {
  local subject="$1"
  local message="$2"
  echo -e "$message" | mail -s "$subject" "$EMAIL_RECIPIENT" || {
    echo "Error: Failed to send email alert." >&2
  }
}

# Get disk usage percentage for the specified path
# Using 'df -h' for human-readable, then 'awk' to get the percentage of the specific mount point
# The regex '[0-9]+%' handles different formatting of 'df' output for the percentage column
USED_PERCENT=$(df -h "$CHECK_PATH" | awk 'NR==2 {print $5}' | sed 's/%//g')

# Validate if USED_PERCENT is a number
if ! [[ "$USED_PERCENT" =~ ^[0-9]+$ ]]; then
  echo "Error: Could not retrieve disk usage percentage for '$CHECK_PATH'." >&2
  exit 1
fi

echo "Current disk usage for $CHECK_PATH: $USED_PERCENT%"

# Check if usage exceeds the threshold
if (( USED_PERCENT >= THRESHOLD )); then
  ALERT_MESSAGE="Disk space usage on $(hostname) for $CHECK_PATH is at ${USED_PERCENT}% which exceeds the ${THRESHOLD}% threshold.
Please take action immediately."
  echo "$ALERT_MESSAGE"
  send_alert_email "$EMAIL_SUBJECT" "$ALERT_MESSAGE"
  exit 1 # Exit with error code to indicate an issue
else
  echo "Disk space usage for $CHECK_PATH is healthy (${USED_PERCENT}% < ${THRESHOLD}%)."
  exit 0 # Exit successfully
fi
How it works: This Bash script monitors the disk space usage of a specified path (defaulting to the root filesystem). It uses `df -h` to get human-readable disk statistics and `awk` to extract the percentage used. The script then compares this percentage against a predefined `THRESHOLD`. If the usage exceeds the threshold, a critical alert message is printed and an email is sent to a configured recipient (requiring the `mail` command to be set up). This is a vital tool for web developers to prevent server outages due to full disks, ensuring system stability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs