Linux disk usage monitor script

I found that Azure has a hard time to monitor disk usage on a Linux box. There are ways, but it seems to be too complicated to achieve such a basic thing. So I came up with the following script I call in a cron job as needed.

#!/bin/bash
CURRENT=$(df / | grep / | awk '{ print $5}' | sed 's/%//g')
THRESHOLD=90
PUBLICIP=$(curl ipecho.net/plain)
LOCALIP=$(ips=($(hostname -I))
for ip in "${ips[@]}"
do
 echo $ip
done)

if [ "$CURRENT" -gt "$THRESHOLD" ] ; then
    mail -a From:[email protected] -s "Disk Space Alert on ${HOSTNAME} ($PUBLICIP / $LOCALIP)" [email protected] << EOF
The $HOSTNAME root partition remaining free space is critically low. Used: $CURRENT%
EOF
fi
Linux disk usage monitor script

Make sure to adjust the THRESHOLD and emails as needed. Ideally, you’ll configure a mail server (e.g. Postfix) with SMTP credentials (e.g. SendGrid) and proper SPF records to make sure your emails don’t end up in Junk and miss them.

There are plenty of proper monitoring solutions and I always love those that give you a free tier such as HetrixTools Uptime Monitors or Datadog. However, not always these can be used.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.