Running out of disk space can cause significant issues, including system crashes and data loss. This Bash script monitors the disk space usage of a specified directory and sends an email alert if the usage exceeds a defined threshold.

Step-by-Step Guide:

1. Define Variables: Set the threshold percentage for disk usage and the email address to receive alerts.

THRESHOLD=80

EMAIL="your_email@example.com"

2. Check Disk Usage: Use the df command to get the disk usage of the specified directory.

DISK_USAGE=$(df /path/to/directory | grep / | awk '{ print $5 }' | sed 's/%//g')

3. Send an Email Alert: If the disk usage exceeds the threshold, send an email alert.

if [ $DISK_USAGE -gt $THRESHOLD ]; then

echo "Disk space warning: $DISK_USAGE% used" | mail -s "Disk Space Alert" $EMAIL

fi

Complete Script:

#!/bin/bash

# Variables
THRESHOLD=80
EMAIL=“your_email@example.com”
DISK_USAGE=$(df /path/to/directory | grep / | awk ‘{ print $5 }’ | sed ‘s/%//g’)

# Check disk usage
if [ $DISK_USAGE -gt $THRESHOLD ]; then
echo “Disk space warning: $DISK_USAGE% used” | mail -s “Disk Space Alert” $EMAIL
fi

Usage:

  • Replace /path/to/directory with the directory to monitor.
  • Set THRESHOLD to the desired percentage.
  • Replace your_email@example.com with your email address.
  • Save it to .sh file (ie. diskspacealert.sh) and run it periodically with a crontab

This script ensures you are promptly notified if your disk space is running low, allowing you to take action before it becomes a critical issue.