Shell Script for Disk Space Notification

Shell Script for Disk Space Notification

The Disk Space Notification script can be scheduled to run once in a week which will check the Disk Space Usage on the server. The Shell script will send out an email to the admin if the Disk Space Usage is greater than the Threshold.

Create a file /home/diskspace.sh and paste the following code in it:

#!/bin/sh

#Threshold is set to 70 here.
THRESHOLD=70
MAILTO=”youremailaddress”
TEMPFILE=/tmp/diskspace.temp
HOSTNAME=`hostname`

rm -f $TEMPFILE

#Calculate the Current Disk Usage with the below command.
CDU=$(df -h | tail -1 | awk ‘{print $5}’ | sed ‘s/%//’)

#Compare the current value with the threshold one.
if [ $(expr $CDU “>=” $THRESHOLD) -ne 0 ]
then
echo “Warning!!! Disk Space usage on server $HOSTNAME is ${CDU}%” >> $TEMPFILE
fi

#Send an email if /tmp/diskspace.temp is present.
if [ -e $TEMPFILE ]
then
mail -s “Disk Space Notification” $MAILTO < $TEMPFILE
fi

rm -f $TEMPFILE

Save the file. Now you need to schedule a cron to execute the script once in a week.

crontab -e

and set the following cronjob:

0 1 * * 0  /bin/sh  /home/diskspace.sh

Save the file and restart the crond service. The cronjob will now execute on Sunday at 1.00AM and will send a notification if the disk space usage on the server is above the threshold.

This entry was posted on Friday, November 13th, 2009 and is filed under Scripts. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

4 Responses to “Shell Script for Disk Space Notification”

  1. Aaron

    Thanks for the script! Why don’t you send the email in the first conditional instead of writing the temp file?

  2. admin

    Aaron, thanks for trying the script.
    Yes, the output can be send directly without saving it in the file, however, if there are more things to email, it is useful to save it in a file and then email. It\’s a good habit 🙂

  3. Jan

    Hey, thanks for the script, saved me from building one with PHP 😉 – I’m not that good at shell scripting to create one myself… Regards, Jan

  4. admin

    No problems 🙂