Shell Script to Monitor Disk Usage

Summary: Monitor disk space and send alerts.


System administrators know that running out of disk space can cause applications or services to crash, leading to downtime and potentially, data loss. Automating disk usage monitoring and alerting can save time and prevent these disasters. In this article, we delve into how to write a simple yet effective shell script to monitor disk usage and send alerts when thresholds are reached.

Why Monitor Disk Usage?

Monitoring disk usage proactively helps you:

  • Avoid unexpected downtime.
  • Ensure critical applications have the resources they need.
  • Maintain logs and backups without interruptions.
  • Diagnose possible attacks (like logs filling due to malicious activity).

The Basics: df Command

Linux systems provide the df command to check disk space usage:

df -h
  • -h shows values in human-readable format.

Sample output:

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        50G   35G   12G  75% /

We can use awk or grep to filter output for our script.

Step-by-Step Script Breakdown

Below, we’ll build a script that:

  1. Checks disk usage.
  2. Compares usage to a threshold (e.g., 80%).
  3. Sends an email alert if usage exceeds the threshold.

1. Setting the Threshold

Let’s use 80% as our critical limit:

THRESHOLD=80

2. Parsing Used Disk Percentage

Use df and awk to extract the usage percentage (removing the %):

USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
  • NR==2 skips header, picks root filesystem (adapt as needed).
  • print $5 displays the Usage % column.
  • sed 's/%//' removes the %-sign.

3. Sending an Alert

Use mail or mailx to send an email. Adjust the recipient and subject as needed.

Complete Script

Here’s the complete shell script. Save as disk_monitor.sh and make it executable (chmod +x disk_monitor.sh):

#!/bin/bash

# Disk usage threshold (in percent)
THRESHOLD=80

# Filesystem to monitor (e.g., root '/')
FILESYSTEM="/"

# Email settings
EMAIL="admin@example.com"
SUBJECT="Disk Usage Alert on $(hostname)"

# Get the current disk usage as a percentage (no % sign)
USAGE=$(df -h $FILESYSTEM | awk 'NR==2 {print $5}' | sed 's/%//')

# Check if the disk usage is greater than or equal to the threshold
if [ "$USAGE" -ge "$THRESHOLD" ]; then
    MESSAGE="Warning: Disk usage on $FILESYSTEM is at ${USAGE}% as of $(date).\n\n$(df -h $FILESYSTEM)"
    echo -e "$MESSAGE" | mail -s "$SUBJECT" $EMAIL
fi

Note:

  • Replace $EMAIL with your actual admin or notification email.
  • Ensure your system is configured to send emails (e.g., with mailx, ssmtp, or Postfix).

Scheduling the Script (Cron Job)

To run this script every hour, add this to your crontab (crontab -e):

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

This checks usage hourly and sends alerts as needed.

Customizing the Script

  • Multiple Filesystems: Loop through all critical mounts.
  • Different Notification Methods: Use sendmail, Slack API hooks, or SMS integrators.
  • Logging: Append alerts to a log file for auditing.

Conclusion

With this straightforward shell script, you can automate disk space monitoring and receive timely alerts before space runs out. This proactivity helps avoid outages and keeps your systems running smoothly.

Have feedback or suggestions? Share your thoughts below!