Linux Shell Script To Monitor Space Usage and Send Email

7829

Linux shell script to check /var logs space and send email if used space reach 80%. Also print space usage of each directory inside /var. Useful to find out which folder use most of space under /var. This script really helps system administrator to monitor their servers space usage. Based on the requirement , administrators can change the directoires they want to monitor.

 

#!/bin/bash

LIMIT=’80’

#Here we declare variable LIMIT with max of used spave

DIR=’/var’

#Here we declare variable DIR with name of directory

MAILTO=’
This e-mail address is being protected from spambots. You need JavaScript enabled to view it

#Here we declare variable MAILTO with email address

SUBJECT=”$DIR disk usage”

#Here we declare variable SUBJECT with subject of email

MAILX=’mailx’

#Here we declare variable MAILX with mailx command that will send email

which $MAILX > /dev/null 2>&1

#Here we check if mailx command exist

if ! [ $? -eq 0 ]

#We check exit status of previous command if exit status not 0 this mean that mailx is not installed on system

then

          echo “Please install $MAILX”

#Here we warn user that mailx not installed

          exit 1

#Here we will exit from script

fi

cd $DIR

#To check real used size, we need to navigate to folder

USED=`df . | awk ‘{print $5}’ | sed -ne 2p | cut -d”%” -f1`

#This line will get used space of partition where we currently, this will use df command, and get used space in %, and after cut % from value.

if [ $USED -gt $LIMIT ]

#If used space is bigger than LIMIT

then

      du -sh ${DIR}/* | $MAILX -s “$SUBJECT” “$MAILTO”

#This will print space usage by each directory inside directory $DIR, and after MAILX will send email with SUBJECT to MAILTO

fi

Sample Output

./check_var.sh

37M     /var/cache

32K     /var/db

8.0K    /var/empty

4.0K    /var/games

70M     /var/lib

4.0K    /var/local

8.0K    /var/lock

38M     /var/log

0       /var/mail

4.0K    /var/nis

4.0K    /var/opt

4.0K    /var/preserve

88K     /var/run

220K    /var/spool

37M     /var/tmp

24M     /var/www

4.0K    /var/yp

Read more linux shell scripts