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
1 |
df / |
As you can see, the result have 2 lines. We don’t need first line. To ignore first line, we can use
1 |
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.
1 |
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
1 |
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.
1 |
vi disk-usage-checker |
Add following content to it
1 2 3 4 5 6 7 8 9 10 |
#!/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.
You can run the script daily using cronjob. If disk usage ever go above 80%, you will get email alert.
See bash