Skip to content

Instantly share code, notes, and snippets.

@M1ke
Last active June 11, 2024 09:18
Show Gist options
  • Save M1ke/5300297 to your computer and use it in GitHub Desktop.
Save M1ke/5300297 to your computer and use it in GitHub Desktop.
A shell script to check your disk usage and alert you if it hits a limit. Change the value (percentage) in the "if" statement on line 7 to alter the threshold. Change the email address to your email address. See readme for mail.cf instructions and crontab.

Disk Usage Alerter

Install mailutils with:

sudo apt-get install mailutils

Set up the cronjob with:

crontab -e

To send at 10 mins past the hour add:

10 * * * * sh /path/to/script

If you'll be emailing the same domain that your mailname is set to:

Navigate to /etc/postfix/

sudo vi main.cf

Find line beginning mydestination, it should say something like:

mydestination =  ubuntu, localhost.localdomain, localhost

Crucially it shouldn't contain your mailname or references to it, or your emails will be sent internally on the server.

#!/bin/sh
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
echo $output
used=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge 80 ]; then
echo "The partition \"$partition\" on $(hostname) has used $used% at $(date)" | mail -s "Disk space alert: $used% used" your@email.com
fi
done
@bennuttall
Copy link

Is that a typo on line 7? Guess it should read $used not $usep

@seenusankara
Copy link

Disk_Usage.sh: line 6: [: -gt: unary operator expected
rootfs 10319160 7903188 1891788 81% /
Disk_Usage.sh: line 6: [: -gt: unary operator expected
[6] 13:40:59 [SUCCESS] 10.34.29.185
Disk_Usage.sh: line 6: [: -gt: unary operator expected
rootfs 10319160 7634140 2160836 78% /
Disk_Usage.sh: line 6: [: -gt: unary operator expected
[7] 13:40:59 [SUCCESS] 10.34.93.190
Disk_Usage.sh: line 6: [: -gt: unary operator expected
rootfs 10319160 7685008 2109968 79% /
Disk_Usage.sh: line 6: [: -gt: unary operator expected
[8] 13:40:59 [SUCCESS] 10.32.233.179
Disk_Usage.sh: line 6: [: -gt: unary operator expected
rootfs 10319160 4999736 4795240 52% /
Disk_Usage.sh: line 6: [: -gt: unary operator expected
[9] 13:40:59 [SUCCESS] 10.32.249.146
Disk_Usage.sh: line 6: [: -gt: unary operator expected
rootfs 10319160 7323748 2471228 75% /
Disk_Usage.sh: line 6: [: -gt: unary operator expected
[10] 13:40:59 [SUCCESS] 10.34.33.22
Disk_Usage.sh: line 6: [: -gt: unary operator expected
rootfs 10319160 7542516 2252460 78% /
Disk_Usage.sh: line 6: [: -gt: unary operator expected

@HareshChhelana
Copy link

@seenusankara replace $usep with $used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment