Linux & Open SourceTechnology

How to Write a Bash Script That Emails You When Disk Usage Passes 90%

Admin
How to Write a Bash Script That Emails You When Disk Usage Passes 90%

A full disk rarely announces itself politely. It shows up as a failed update, a database that stops writing, or a backup that quietly did nothing. By the time you notice, you are already fixing damage instead of preventing it. A small warning, sent while there is still time to act, changes that story completely.

You do not need expensive monitoring software for a personal machine or a small server. A short Bash script that checks disk usage and sends an email when a drive passes 90 percent is enough. In this guide you will build that script step by step, test it safely, and schedule it to check your disk every hour on its own.

Quick Answer

Write a Bash script that reads usage with df, extracts the percentage for your main drive, and compares it with 90 using an if test. When the value is higher, send a message with the mail command, for example echo "Disk at 92%" | mail -s "Disk warning" you@example.com. Make the script executable and run it hourly from cron so the check happens automatically.

How the Script Thinks

The script has three simple jobs. First, it asks the system how full the disk is. Second, it decides whether that number is a problem. Third, if it is a problem, it sends you an email and then stops. Nothing else happens on a healthy day, which is exactly what you want from an alert tool: silence when things are fine, and a clear message when they are not.

The main tool is df, short for disk free. Running df -h / shows the size, used space, available space, and percentage used for the root filesystem in a human-friendly format. The percentage column is the number your script will watch. The GNU Coreutils manual for df documents every option if you want to check other filesystems or change the output format later.

Step 1: Make Sure You Can Send Email

Before writing the alert, confirm that command-line mail works on your machine. Many systems need a small mail package installed first.

  1. On Ubuntu or Debian, install the tools with sudo apt install mailutils. This usually brings in a local mail agent as well.
  2. Send yourself a test with echo "test message" | mail -s "Test" you@example.com, using your real address.
  3. Check your inbox, including the spam folder, because a first message from a home server sometimes lands there.
  4. If nothing arrives, check whether your provider blocks outgoing mail from home connections. A small server on a proper hosting plan usually sends mail without trouble.

Getting mail working first matters. If you build the whole script and the test fails, you will not know whether the check or the mail caused the problem. Testing mail on its own keeps the two halves separate and easy to debug.

Step 2: Write the Disk Check Script

Create a scripts folder if you do not have one, then open a new file with nano ~/scripts/disk-alert.sh. The script below checks the root filesystem, but you can change the path to any mount point, such as /home or /data, if that is the drive you care about most.

Here is the script, explained line by line. Start with #!/bin/bash. Then set your settings: THRESHOLD=90, EMAIL="you@example.com", and PARTITION="/". Next, read the usage: USAGE=$(df "$PARTITION" | awk 'NR==2 {print $5}' | tr -d '%'). Then make the decision: if [ "$USAGE" -ge "$THRESHOLD" ]; then followed by echo "Warning: $PARTITION is at ${USAGE}% full on $(hostname)" | mail -s "Disk alert: ${USAGE}% used" "$EMAIL" and finally fi.

Understanding the Usage Line

That one long line does three small things. The df command prints a table, and awk 'NR==2 {print $5}' picks the fifth column of the second row, which is the percentage such as 92%. The tr -d '%' part removes the percent sign, leaving a plain number. A plain number is essential, because the -ge test means greater than or equal to, and it only works with numbers, not with text like 92%.

The $(hostname) part inserts the machine name into the message. If you look after more than one computer, that detail tells you instantly which one needs attention. Small touches like this make an alert useful instead of vague.

Step 3: Make It Executable and Test It

Save the file, then run chmod +x ~/scripts/disk-alert.sh. Now test in two stages so you can trust both halves of the script.

  1. Run the script as it is with ~/scripts/disk-alert.sh. On a healthy disk below 90 percent, nothing should happen and no email should arrive. That silence is the correct result.
  2. Temporarily change THRESHOLD to a low number such as 10 and run the script again. Almost any real disk is above 10 percent, so an alert email should arrive within a minute or two.
  3. Read the email and confirm the percentage and hostname look right.
  4. Change THRESHOLD back to 90 before you forget. A script left at 10 will mail you every single time it runs.

This low-threshold test is the safest way to prove the alert path works without filling your disk on purpose. Never fill a real drive just to test an alert; a nearly full system can behave badly in ways that are hard to undo. If you maintain several machines, our guide on fixing a cron job that fails when scheduled will help you keep these scheduled checks reliable on all of them.

Step 4: Schedule the Check With Cron

An alert script only helps if it runs regularly. Hourly is a good balance: frequent enough to catch a fast-filling disk, and light enough that the check itself costs almost nothing.

  1. Open your crontab with crontab -e.
  2. Add the line 0 * * * * /home/yourname/scripts/disk-alert.sh, using your real username and full path.
  3. Save the file. The job now runs at the start of every hour.
  4. Optionally add >> ~/disk-alert.log 2>&1 to the line if you want a record of any errors.

One improvement is worth adding once the basic version works: avoid sending the same warning every hour for days. A simple approach is to accept hourly mail during a real incident, because the repetition underlines the urgency. A calmer approach stores the last alert date in a small file and only mails once per day. Start simple, live with it for a week, and refine only if the volume bothers you. The GNU Bash manual is the authoritative reference for the test operators and conditionals used in scripts like this one.

Common Mistakes and Useful Tips

  • Comparing text instead of a number. If you forget to strip the percent sign, the comparison fails or behaves strangely. Always clean the value with tr -d '%'.
  • Checking the wrong filesystem. The root drive may be fine while a separate data drive is full. Add a second check for any mount point that holds large or growing files.
  • Testing only the healthy case. A script that stays silent might be working, or it might be broken. The low-threshold test proves the email path before you depend on it.
  • Ignoring the spam folder. First alerts from a new machine often land in spam. Mark them as not spam so future warnings reach your inbox properly.
  • Setting the threshold too high. At 99 percent you have almost no time left. Ninety percent gives you room to delete, move, or expand before services start failing.
  • Forgetting who receives the mail. If you change email addresses, update the script. An alert sent to an address nobody reads is the same as no alert at all.

Conclusion

With about fifteen lines of Bash, you now have a watchdog for your disk: df measures usage, an if test compares it with 90, and mail warns you while there is still time to act. Test it with a low threshold, schedule it hourly with cron, and a full disk stops being a surprise emergency. It becomes a routine message you can handle calmly, on your own schedule.

Frequently Asked Questions

What should I do when I receive a 90 percent alert?

Act the same day. Find the largest folders with a disk usage tool, clear caches and old downloads, remove old backups you no longer need, and consider moving large media to another drive. The alert buys you time, but only if you use it.

Can I check more than one drive with this script?

Yes. Copy the usage and test lines for each mount point, or turn the check into a small loop over a list of partitions. Give each alert its own message so you know exactly which drive is filling up.

My test email never arrives. What should I check?

Confirm the mail package is installed, test the mail command on its own, and look in your spam folder. On home connections, some providers block outgoing mail, so a relay or a hosted server may be needed.

Why use 90 percent instead of 95 or 80?

Ninety percent is a practical balance. At 80 percent many healthy systems would warn too often, while at 95 percent a fast-growing log or backup could fill the rest before you react. Adjust it to how quickly your disk normally fills.

Can I send the alert to more than one person?

Yes. Put several addresses in the mail command separated by commas, or mail a group address. For a shared server, sending the warning to everyone who can act on it is a sensible choice.

Admin

Passionate about the intersection of style and storytelling. I simplify fashion trends and industry news into easy-to-follow advice, helping you stay stylish and informed in the fast-paced world of fashion.

Leave a Reply

Your email address will not be published. Required fields are marked *