Get Social

Bash script in one line to check free space in Linux

This task arose after the client sites were moved from the old VPS to the new one. On the new virtual server, everything is fine with the processor and the RAM, but the disk space is very close. It turned out that Vesta CP, which by default creates 3 backups, just filled the disk to zero.

The client asked me that when the place becomes small – it immediately became known. So I decided to make a very simple script “in one line”, which tracks disk space and sends a notification to e-mail. Such a script can be completely inserted in the Cron scheduler.

Actually, here it is:

Linux disk space monitoring script


if [ "`df | grep "/dev/sda1" | awk '{print $5}' | sed 's/\%//'`" -ge 95 ]; then echo "Disk usage exceeded 95%" | mail -s "Warning! My Server" mail@example.com; fi

When the disk usage reaches 95%, this one-line script will start sending messages with warnings to the mail “mail@example.com”. For example, you can add this line to the cron to check every 45 minutes. Of course, you can set it for every minute, but then your mailbox will just be fill up with these messages.

You can also go ahead and do so that we have one more warning when you reach 99%:

if [ "`df | grep "/dev/sda1" | awk '{print $5}' | sed 's/\%//'`" -ge 99 ]; then echo "Disk usage exceeded 99%!" | mail -s "Panic!! My Server" mail@example.com; fi

The situation is more serious here, so you can put in the cron to check every 5 minutes

As a result, we get in crontab:

# server usage alert
*/45 * * * * if [ "`df | grep "/dev/sda1" | awk '{print $5}' | sed 's/\%//'`" -ge 95 ]; then echo "Disk usage exceeded 95%" | mail -s "Warning! My Server" mail@example.com; fi
*/5 * * * * if [ "`df | grep "/dev/sda1" | awk '{print $5}' | sed 's/\%//'`" -ge 99 ]; then echo "Disk usage exceeded 99%!" | mail -s "Panic!! My Server" mail@example.com; fi

Of course, you can go even further and make these scripts to one script in a separate file and with a nice syntax and indentations. But the above option just works and it’s enough for me.

P.S. Make sure that you have the correct disk (“/dev/sda1” or something else) in the output of the df command.

Post a comment