How to Automatically Send an Email Alert When a Linux Server is Low on Disk Space

When a Linux server runs out of disk space, critical services like databases (MySQL, PostgreSQL) and web servers (Nginx, Apache) will crash immediately because they can no longer write to their log files. To prevent catastrophic downtime, system administrators must be notified the moment a storage drive approaches full capacity. While enterprise monitoring tools exist, you can create a lightweight, automated disk space alert system using a simple bash script and the cron daemon.

How to Create the Disk Monitoring Script

We will write a shell script that checks the capacity of the root partition (/). If the usage exceeds 90%, it will send an email alert using the mail command.

  1. Log into your Linux server via SSH.
  2. Ensure you have a mail utility installed. On Ubuntu/Debian, you can install mailutils by running: sudo apt install mailutils -y
  3. Create a new script file in your home directory: nano ~/disk_monitor.sh
  4. Paste the following code into the file:
    #!/bin/bash
    # Set your alert threshold (e.g., 90%)
    THRESHOLD=90
    # Set the email address to receive the alert
    EMAIL="[email protected]"
    
    # Check the root partition (/) usage, removing the % sign
    CURRENT_USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    
    if [ "$CURRENT_USAGE" -ge "$THRESHOLD" ]; then
        MESSAGE="WARNING: The root partition on $(hostname) is currently at ${CURRENT_USAGE}% capacity."
        echo "$MESSAGE" | mail -s "Disk Space Alert: $(hostname)" "$EMAIL"
    fi
  5. Save the file (press Ctrl+O, Enter, then Ctrl+X).
  6. Make the script executable: chmod +x ~/disk_monitor.sh

How to Automate the Script via Crontab

The script works perfectly, but it must be run continuously to be useful. We will use the cron daemon to execute the script automatically every hour.

  1. Open your crontab editor: crontab -e
  2. Add the following line to the bottom of the file: 0 * * * * /home/yourusername/disk_monitor.sh
  3. Save and exit the crontab editor.

The server will now silently check its disk capacity at the top of every hour. If the usage spikes above 90%, it will immediately dispatch an email to the administrator, allowing you to SSH into the machine and clear old log files before the server crashes.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.