Linux Shell Script To Check Disk Usage Is Out Of Space

March 5, 2013 | By
| Reply More

Script that check used space on all mounted devices and warn if the used space is more than the threshold. In this scenario we were using 25% of disk, that's why threshold is so small.

more shell scripts

Linux Shell Script

#!/bin/bash

threshold="20"

i=2

result=`df -kh |grep -v "Filesystem" | awk '{ print $5 }' | sed 's/%//g'`

for percent in $result; do

if ((percent > threshold))
then

partition=`df -kh | head -$i | tail -1| awk '{print $1}'`

echo "$partition at $(hostname -f) is ${percent}% full"

fi

let i=$i+1

done

Test Script Result

bobbin@linoxide:/$ df -kh
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 52G 4.7G 45G 10% /
tmpfs 1.9G 0 1.9G 0% /lib/init/rw
udev 1.9G 192K 1.9G 1% /dev
tmpfs 1.9G 2.6M 1.9G 1% /dev/shm
/dev/sda6 92G 22G 66G 25% /home

bobbin@linoxide:/$ ./df_script.sh
/dev/sda6 at linoxide.lviv.example.com is 25% full

Learn Above Shell Script

#This set threshold value

threshold=”20″

#Counter, will be used later, set to 2, since first line in df output is description.

i=2

#Getting list of percentage of all disks, df -kh show all disk usage, grep -v – without description line, awk ‘{ print $5 }’ – we need only 5th value from line and sed ‘s/%//g’ – to remove % from result.

result=`df -kh |grep -v “Filesystem” | awk ‘{ print $5 }’ | sed ‘s/%//g’`

#for every value in result we start loop.

for percent in $result; do

#compare, if current value bigger than threshold, if yes next lines.

if ((percent > threshold))

then

#taking name of partition, here we use counter. Df list of all partitions, head – take only $i lines from top, tail -1 take only last line, awk ‘{print $1}’ – take only first value in line.

partition=`df -kh | head -$i | tail -1| awk ‘{print $1}’`

#print to console – what partition and how much used in %.

echo “$partition at $(hostname -f) is ${percent}% full”

#end of if loop

fi

#counter increased by 1.

let i=$i+1

#end of for loop.

done

Filed Under : SHELL SCRIPTS

Tagged With :

Free Linux Ebook to Download

Leave a Reply

Commenting Policy:
Promotion of your products ? Comment gets deleted.
All comments are subject to moderation.