Shell Script to Watch Disk Space

The first step in your fancy Bash script is to get disk space like this.

 df -h


Filesystem Size Used Avail Use% Mounted on
/dev/sda1 7.6G 784M 6.4G 11% /
tmpfs 249M 0 249M 0% /lib/init/rw
udev 244M 192K 244M 1% /dev
tmpfs 249M 0 249M 0% /dev/shm
/dev/md0 2.0G 35M 2.0G 2% /storage

Next, let’s focus on grabbing the percentage of space used on each device..

df -H | grep -vE '^Filesystem|none|cdrom' | awk '{ print $5 " " $1 }'


 11% /dev/sda1 0% tmpfs 1% udev 0% tmpfs 2% /dev/md0

Shell Script

Let’s take this info and write a simple shell script. The previous command displays fields 5 and 1 of the df command. Now all you need to do is write a script to see if the percentage of space is >= 90%.

 mkdir /root/scripts/diskAlert nano /root/scripts/diskAlert

and paste.

df -H | grep -vE '^Filesystem|none|cdrom' | awk '{ print $5 " " $1 }' | while read output;
 echo $output
 usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
 partition=$(echo $output | awk '{ print $2 }' )
 if [ $usep -ge 90 ]; then
 echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
 mail -s "Alert: Almost out of disk space $usep%"

Replace with your proper email account. Next, we’ll need to set it up as executable and add it to our cronjobs.

chmod +x /root/scripts/diskAlert

Install as cronjob:

crontab -e

Finally, add this to your cronjob list.

10 0 * * * /root/scripts/diskAlert

This will make it run at 12:10 A.M. every day. It will automatically email an alert if you’re over 90% used on any one of your volumes.


I love learning new things and trying out the latest technology.

You may also like...

Leave a Reply

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