Check free disk space in Linux
With a simple shell script, you can monitor your server's free disk space and send an email alert if it exceeds a threshold.
Running out of disk space on a server is easy, and it can have serious consequences—for example, you might end up with corrupted MySQL tables.
Inodes can also be exhausted. If you’re not sure why you’re using so many inodes, it may be because an application is creating a lot of temporary files that aren’t cleaned up. A common example is PHP session files when the garbage collector (GC) isn’t clearing them properly.
Below is an example script that can be run from crontab. It will email you when disk space or inode usage exceeds 90%.
Please note that to send outgoing email, you need to set up a working SMTP server, such as Postfix. See Sending email from your server using Postfix for instructions on how to set up Postfix.
#!/bin/bash
# A small shell script to check disk and inode usage
FROM_EMAIL=some@email.com # The sender of the alert email
TO_EMAIL=some@example.com # The recipient of the alert email
LIMIT=90 # Percent (when to send email)
HOSTNAME=`hostname -f`
# Check all mount points
for i in `df |awk '{print $5}'|grep -v Use|sed 's/\%//'` ; do
if [ $i -gt $LIMIT ];then
(/usr/bin/printf "From: $FROM_EMAIL\nTo: $TO_EMAIL\nSubject: Disk alert on $HOSTNAME\n\n" ; echo "Disk is $i percent full") | /usr/sbin/sendmail -f$FROM_EMAIL $TO_EMAIL
fi
done
for i in `df -x vfat -x fat -i |awk '{print $5}'|grep -v Use|sed 's/\%//'` ; do
if [ $i -gt $LIMIT ];then
(/usr/bin/printf "From: $FROM_EMAIL\nTo: $TO_EMAIL\nSubject: Disk alert on $HOSTNAME\n\n" ; echo "Inode use $i percent") | /usr/sbin/sendmail -f$FROM_EMAIL $TO_EMAIL
fi
doneBefore running the script, you need to make it executable with chmod +x monitor-disk-usage.sh.
Crontab example
Edit your crontab using crontab -e. To run the script every 6th hour, add the following line (change /path/to/script to the path where the script is stored on the server).
Last updated
Was this helpful?