Monitoring disk space is crucial to ensure that servers and systems do not run out of space, which could lead to data loss or system failures. In this article, you will learn how to create a Bash script that monitors disk space and sends an email notification when the available space falls below a specific threshold.
Steps to Create the Script
1. Create the Bash Script:
Create a script file, for example, `monitor_space.sh`:
“`bash
#!/bin/bash

# Configuration
THRESHOLD=20 # Minimum percentage of free disk space
EMAIL=”youremail@example.com”

# Get the percentage of free disk space
FREE_SPACE=$(df / | grep / | awk ‘{ print $4 }’ | sed ‘s/%//g’)

# Check if free space is below the threshold
if [ “$FREE_SPACE” -lt “$THRESHOLD” ]; then
# Send warning email
echo “Warning: Disk space is below $THRESHOLD%. Available space: $FREE_SPACE%.” | mail -s “Alert: Low Disk Space” $EMAIL
fi
“`

2. Set Permissions:
Make sure the script has execution permissions:
“`bash
chmod +x monitor_space.sh
“`

3. Configure Cron Job:
To run the script periodically, you can set it up in cron:
“`bash
crontab -e
“`
Add the following line to run the script every hour:
“`bash
0 * * * * /path/to/script/monitor_space.sh
“`

Conclusion
With this simple script, you can effectively monitor disk space and receive email alerts when space is low, allowing you to take preventive actions.