Cron script for checking disk space

Here is script for those that interested in not installing a daemon like monit, and just rely on a simple bash script to send notifications when the disk space is low. It is a quite common of a server crashing even though it has been well configured, that rotates logs, etc, but still receives an incoming stream of that that needs to be stored and served (databases growing, upload of images, etc).

For installing the script, to check the disk space every hour, with root permissions:

while [ -z "$MAIL_TO" ] ; do echo -n "Disk alert notification email address: " ; read MAIL_TO; done
wget -O /etc/cron.hourly/check-disk-space
chmod +x /etc/cron.hourly/check-disk-space
# will setup a default config file
# set your own email here
sed -i "s/root@localhost/$MAIL_TO/" /etc/check-disk-space.conf

After running the script once, it will populate the configuration file /etc/check-disk-space.conf, do not forget to tune the variables: MIN_DISK_FREE,MIN_DISK_FREE_PANIC and MAIL_TO. The configuration is self documented:

# config

# minimum disk space free
# can be specified in percent (% char at the end) or number of 1K blocks

# send an alert every time the script is executed and this value has been exceeded
# can be specified in percent (% char at the end) or number of 1K blocks
# should be less than the above value if required to be active.

# reminder interval, in seconds, big value like 9999999999 for “disable”.
# reminder is sent if min disk free is still exceed and the interval has passed.

# send alert mail message every time the script is executed, no matte what, good for testing and debugging

# where to send the alert

# mail subject, carefull with the quotation
MAIL_SUBJECT=”$(hostname) is running low on disk space”

# mail message, carefull with the quotation
MAIL_MESSAGE=”host: $(hostname)
minimun required disk free: $MIN_DISK_FREE
$(df -h)

the server is running low on disk space. Maybe there are some large logs to remove, or the disk needs resizing.”

# vars to keep track of the change, no need to change the following

4 responses to “Cron script for checking disk space”

  1. The percent handling is broken. When MIN_DISK_FREE ends in %, the percent is stripped before it is treated as an integer in the -gt and -lt checks. But the Percent is not stripped from MIN_DISK_FREE_PANIC. Hence:
    ./check-disk-space: line 63: [: 1%: integer expression expected

    This is easy enough to add:

    > 	MIN_DISK_FREE_PANIC=$(echo $MIN_DISK_FREE_PANIC | sed 's/%$//g')

    For fiddly to fix is that since AVAILABLE_DISK is only run once with either block or percent output, you cannot mix and match % and block counts for the two settings.

    • Hi, thanks for the report, I have pushed new changes to handle this, should be in the repo in around an hour. It is pending if I will add any variables support, like K,M, etc.