Bash Script to Monitor Disk Usage

This script will check disk usage on / partition and email you if disk usage is above 80%

We can use df / command to find current disk usage

df /

As you can see, the result have 2 lines. We don’t need first line. To ignore first line, we can use

df / | grep -v 'Filesystem'

From the result, we only need the Use% part. In this case 66%, to find this, you can use awk command, that split the line, then prient specified part. In our case, we need 5th part.

df / | grep -v 'Filesystem' | awk '{print $5}'

To use disk usage % in our script for calculation, we need it converted to number. That is remove %. This can be done with sed command

df / | grep -v 'Filesystem' | awk '{print $5}' | sed 's/%//g'

Now we have disk usage as a number. We can use it in our script.

vi disk-usage-checker

Add following content to it

#!/bin/bash

CURRENT_USAGE=$(df / | grep -v 'Filesystem' | awk '{print $5}' | sed 's/%//g')
ALERT_ON=80

if [ "$CURRENT_USAGE" -gt "$ALERT_ON" ] ; then
    mail -s 'Disk Usage Warning' YOUR_EMAIL_HERE << EOF
Disk almost full on / partition. Current Useage: $CURRENT_USAGE%
EOF
fi

In above script, replace YOUR_EMAIL_HERE with your email address.

disk usage bash script

You can run the script daily using cronjob. If disk usage ever go above 80%, you will get email alert.

See bash

Comments

Leave a Reply

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