CopyDisable

Wednesday, 5 December 2012

df command to show long Filesystem name in a single line

I was writing a disk space monitoring script for one of my Ubuntu server. The script was as follows:
df -kh | grep -vE 'Filesystem|cdrom|tmp|non' |awk '{print $5" "$6}' | while read line
do
par=$(echo $line | awk '{print $2}')
per_of_use=$(echo $line | awk '{print $1}' | cut -f1 -d'%')
if [ $per_of_use -ge 85 ]
then
sub="Low disk space in "`hostname`" server"
echo "
Partition $par has low sapce.
$per_of_use % of it is in use.
Kindly free some space.
" | mail -s " $sub "
pranabksharma@gmail.com
fi
done


But when I run the script, it was failing. I checked and found that df command output was the culprit.
The output of df command was coming as
# df -kh
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/SVNServer-root
                      4.5G  3.0G  1.3G  72% /
none                  995M  188K  995M   1% /dev
none                 1002M     0 1002M   0% /dev/shm
none                 1002M  356K 1002M   1% /var/run
none                 1002M  4.0K 1002M   1% /var/lock
/dev/sda1             228M   21M  196M  10% /boot
/dev/sdb1             7.9G  551M  7.0G   8% /home/data
//10.1.49.50/svn-et2012/
                      100G   49G   52G  49% /mnt/svnbackup


We can see that two lines of df command output were getting wrapped, because of the long filesystem names.
So the workaround for this problem will be to use column command along with the df command.
# df -khP | column -t
Filesystem                  Size   Used  Avail  Use%  Mounted         on
/dev/mapper/SVNServer-root  4.5G   3.0G  1.3G   72%   /
none                        995M   188K  995M   1%    /dev
none                        1002M  0     1002M  0%    /dev/shm
none                        1002M  356K  1002M  1%    /var/run
none                        1002M  4.0K  1002M  1%    /var/lock
/dev/sda1                   228M   21M   196M   10%   /boot
/dev/sdb1                   7.9G   551M  7.0G   8%    /home/data
//10.1.49.50/svn-et2012/    100G   49G   52G    49%   /mnt/svnbackup


So my disk space monitoring script will be
df -khP | column -t | grep -vE 'Filesystem|cdrom|tmp|non' |awk '{print $5" "$6}' | while read line
do
par=$(echo $line | awk '{print $2}')
per_of_use=$(echo $line | awk '{print $1}' | cut -f1 -d'%')
if [ $per_of_use -ge 85 ]
then
sub="Low disk space in "`hostname`" server"
echo "
Partition $par has low sapce.
$per_of_use % of it is in use.
Kindly free some space.
" | mail -s " $sub " pranabksharma@gmail.com
fi
done