Script to Watch Disk Space

Watch Disk Space using Bash Script

Some time Space issue cause to crash or hang our server which makes loss of our data which comes from web users. So there is need to monitor disk space which would automatically send mail to us if it reaches some critical values so that we can delete some old or unusable data from server and free some space.

df displays the amount of disk space available on the file system containing each file name argument. If no file name is given, the space available on all currently mounted file systems is shown. Read man page of df if you are new to df command.

Steps to monitor disk space and report us

=> Find disk space using df for each drive

=> Filter out filesystem and find out the percentage of space using grep

=> Write a shell script and send mail to us

Step # 1: First get disk space using df command

$ df -H

Output:

Filesystem             Size   Used  Avail Use% Mounted on
/dev/hdb1               20G    14G   5.5G  71% /
tmpfs                  394M   4.1k   394M   1% /dev/shm
/dev/hdb5               29G    27G   654M  98% /nas/www

Step # 2: Next filter out filesystem and find out the percentage of space

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

Output:

51% /
21% /boot
96% /media/Materials

 

Step # 3: Write a shell script

Above command displays field 5 and 1 of df command. Now all you need to do is write a script to see if the percentage of space is >= 90% (download script):

#!/bin/sh
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $6 }' | while read output;
do
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  partition=$(echo $output | awk '{ print $2 }' )
  if echo $usep | egrep -q '^[0-9]+$'; then
  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%" [email protected]
  fi
fi
done

Setup Cron job

Save and install script as crontab.

install as cronjob

crontab -e

Write cronjob as per your requirement

 0 1 * * * /path/to/scriptalert

 

 

Balvinder Singh

Hello, I am Balvinder Singh - DevOps Engineer with 2.5+ year of working experience with different server environments. Tag Line:-Linux | AWS| WHM |Monitoring | Virtualization | Optimization | Performance | Security | Release & Deployment. I love helping companies / clients to deploy their code / applicateions to well managed, optimized, secure server and can go extra mile to satisfy.

You may also like...

Leave a Reply

Your email address will not be published.