This article contain infromation about shell script to check disk space and send email alerts in linux. I wrote this article for regularly checking the disk usage rates of the PostgreSQL databases that I manage.
You can use the script which I will share to send disk usages to yourself as email for linux systems.
First, you should create a sh file in a directory on your system with the command below.
1 |
vi diskusage.sh |
Then, by pressing the insert from the keyboard, paster the following contents to the file.
In the following script I have listed the parameters you need to change.
yourdiskpart | You should type the disk or mount name. For example /sda1 or /postgres |
x@xyz.com | The email address you want to send the mail to. |
80 | When the Disk Usage Ratio exceeds 80%, it sends email.You can change this number according to your needs. |
y@xyz.com | The email address you want to send the mail from. |
1 2 3 4 5 6 7 8 9 |
#!/bin/bash THRESHOLD=80 EMAIL=x@xyz.com #PART=yourdiskpart PART=/boot USE=`df -h |grep $PART | awk '{ print $5 }' | cut -d'%' -f1` if [ $USE -gt $THRESHOLD ]; then echo "Percent Used: $USE" | mail -s "Disk Usage Rate " -r y@xyz.com $EMAIL fi |
:wq
command.
You must run the following command to grant execute to the file.
1 |
chmod 700 diskusage.sh |
We will then enter crontab with the command crontab -e
and create a job that will run this script every morning at 09:00.
You can access the details of crontab job creation in the article titled “How To Create Crontab Job On Linux“.
After running crontab -e
, we press the insert from the keyboard and paste the following content.
With this line, we will indicate that the file “diskusage.sh” will work every day at 09:00 am.
1 2 |
#disk usage ratio runs on 09:00 AM 00 09 * * * sh /xx/diskusage.sh 2>&1 |
Every morning at 09:00, you will be notified by an email if the disk usage rate of the partition you specified in the diskusage.sh file is over 80%.
If it can not send the email even if the disk usage rate exceeds 80%, it means that you have done something wrong. You can try to solve the problem by running diskusage.sh manually as follows.
1 |
/xx/diskusage.sh |
If there is a problem with sending mail in linux, you can find the problem by using the article named “How To Check Crontab Job Log on Linux“.