How to receive an email alert for disk usage on linux server

Your website may stop functioning properly when disk space gets low. There are a lot of actions and tasks on a website which needs free space on your disk in order to complete. Having low disk space may result in unexpected errors and  failures on your website and sometime it may leave your website non-usable.

View Disk Usage

In general as a server administrator you can view disk usage using df command with -h option..

sudo df -h

It displays Used and Available space on different partitions in a human readable format.

Set an email alert for disk usage on linux server

Since it is a manual task to review disk space usage using above method it is desirable to receive an automated email notification when disk usage is high and available disk space is low.

For example, it will be quite handy to receive an email when a used space threshold has been reached. It allows the server admin to take appropriate action in time.

A shell script placed on the server with the code that takes care of the space usage information and gathering and sending emails can do it. Lets see how.

Create Shell Script

Create a file on your server. In this example I created this script in /var/scripts/ folder.

Put the following code in it

CURRENT=$(df / | grep / | awk '{ print $5}' | sed 's/%//g')

if [ "$CURRENT" -gt "$THRESHOLD" ] ; then
mail -s 'MyServer: Disk Space Critically Low' ${TO_EMAIL} ${CC_EMAIL} << EOF
Hi xxxxx,

Your root partition remaining free space is critically low.

Disk Space Used: $CURRENT%

Server: xxxxxxx
Additional Info: ${SOMEINFO}

Set executable permissions
sudo chmod +x

Test it
sudo sh

Next: Add a Cronjob

Once you have created a shell script with right permissions, tested it you can set up a cron job to monitor disk usage

crontab -e

Paste the following to the end of crontab -e file. Cron will run this script once in an hour.
0 * * * * sh /var/scripts/ > /dev/null 2>&1

(Hint: You can set time interval which suits you)

Restart Cron service

In Redhat/Fedora/Centos

sudo service crond restart

In Debian/Ubutnu
sudo /etc/init.d/cron restart

If everything goes well you should start receiving email alert for disk usage.

Leave a Reply

Your email address will not be published.