1080*80 ad

Disk Usage Monitoring Script with Alerting

Proactive Server Management: A Simple Bash Script for Disk Usage Alerts

Unexpected downtime is a system administrator’s worst nightmare, and one of the most common culprits is a surprisingly simple one: a full disk drive. When a server’s storage reaches capacity, applications can crash, data can become corrupted, and critical services can grind to a halt. Manually checking disk space is inefficient and unreliable. The key to preventing these emergencies is proactive monitoring with automated alerts.

This guide will walk you through creating and deploying a simple yet powerful Bash script to monitor your server’s disk usage and automatically notify you before it becomes a critical issue.

Why Automated Disk Monitoring is Non-Negotiable

Relying on manual checks for disk space is a recipe for disaster. An automated system provides several crucial advantages:

  • Prevents Service Downtime: Receive alerts when usage hits a predefined threshold (e.g., 80%), giving you ample time to free up space or provision more storage before applications are affected.
  • Protects Data Integrity: A full disk can lead to incomplete writes and data corruption. Automated monitoring helps ensure your systems always have the space they need to operate correctly.
  • Enables Proactive Maintenance: Instead of reacting to emergencies, you can perform scheduled cleanups, archive old logs, or expand storage during planned maintenance windows.
  • Saves Time and Resources: Automating this fundamental task frees you up to focus on more complex administrative duties, confident that a critical system metric is being watched.

Building Your Disk Monitoring Script

This script uses standard Linux command-line tools, making it highly portable and easy to implement on almost any server. The logic is straightforward: check the disk usage percentage, compare it to a set threshold, and send an email if the usage exceeds that limit.

Here is the complete script. You can save this file as disk_monitor.sh.

#!/bin/bash

# --- Configuration ---
# Set the percentage threshold for the alert.
THRESHOLD=85

# Set the recipient email address for alerts.
ALERT_EMAIL="[email protected]"

# Set the filesystem to monitor (e.g., "/" for the root filesystem).
FILESYSTEM="/"
# --- End Configuration ---

# Get the current disk usage percentage for the specified filesystem.
# The command chain breaks down as follows:
# 1. df -h: Shows disk usage in a human-readable format.
# 2. grep "$FILESYSTEM": Filters the output to only the line for our target filesystem.
# 3. awk '{print $5}': Prints the 5th column, which is the usage percentage.
# 4. sed 's/%//g': Removes the "%" symbol.
CURRENT_USAGE=$(df -h "$FILESYSTEM" | grep "$FILESYSTEM" | awk '{print $5}' | sed 's/%//g')

# Check if the current usage is greater than the defined threshold.
if [ "$CURRENT_USAGE" -gt "$THRESHOLD" ]; then

  # Get the server's hostname to include in the alert message.
  HOSTNAME=$(hostname)

  # Prepare the email subject and body.
  SUBJECT="Disk Space Alert on $HOSTNAME: Usage is at ${CURRENT_USAGE}%"
  BODY="Critical Warning: Disk usage on server '$HOSTNAME' for filesystem '$FILESYSTEM' has exceeded the threshold of ${THRESHOLD}%. Current usage is ${CURRENT_USAGE}%."

  # Send the email alert.
  # Ensure your server has a mail transfer agent (like mailutils, sendmail, or postfix) configured.
  echo "$BODY" | mail -s "$SUBJECT" "$ALERT_EMAIL"

fi

exit 0

Key components of the script:

  1. Configuration Variables: At the top, you can easily set the THRESHOLD, the ALERT_EMAIL, and the FILESYSTEM you want to monitor. This makes the script easy to adapt without changing the core logic.
  2. Checking Usage: The command df -h is used to get disk information. We then use grep, awk, and sed to isolate the exact numeric percentage for the root filesystem.
  3. Conditional Logic: An if statement compares the CURRENT_USAGE with your THRESHOLD. The alert is only triggered if the usage is higher.
  4. Sending the Alert: If the threshold is breached, the script constructs a clear subject line and body and sends an email using the mail command. You must have a mail transfer agent (MTA) like mailutils or postfix installed and configured on your server for this to work.

Automating the Script with Cron

A monitoring script is only useful if it runs automatically and consistently. The perfect tool for this job is cron, the built-in Linux task scheduler.

Step 1: Make the Script Executable
First, you need to give the script permission to be executed. Navigate to the directory where you saved the file and run:

chmod +x disk_monitor.sh

Step 2: Add a Cron Job
Next, open your crontab file for editing:

crontab -e

This will open a text editor. Add the following line to the end of the file to schedule the script to run once every hour, at the top of the hour.

0 * * * * /path/to/your/disk_monitor.sh

Make sure to replace /path/to/your/disk_monitor.sh with the actual, absolute path to your script. Save and close the file. The cron daemon will now automatically execute your monitoring script every hour.

Security and Best Practices

  • Use Specific Filesystems: While monitoring the root (/) filesystem is essential, consider creating copies of this script to monitor other critical mount points, like /var (for logs) or /home.
  • Error Logging: For more robust monitoring, you can redirect the script’s output to a log file to track when it runs and if any errors occur. You can modify the cron job like this: 0 * * * * /path/to/your/disk_monitor.sh >> /var/log/disk_monitor.log 2>&1
  • Consider Advanced Alerting: For production environments, you might want to integrate alerts with services like Slack, PagerDuty, or a centralized monitoring platform instead of just email. This can be achieved by replacing the mail command with an API call.
  • Use a Dedicated User: For enhanced security, avoid running maintenance scripts as the root user whenever possible. Create a dedicated, non-privileged user for running monitoring tasks.

By implementing this simple, automated solution, you can move from a reactive to a proactive server management strategy, ensuring system stability and preventing one of the most common causes of service interruptions.

Source: https://www.tecmint.com/monitor-disk-usage-bash-script/

900*80 ad

      1080*80 ad