Friday, June 05, 2009

[Shell script] Monitor Disk space

#!/bin/bash
USAGE_SPACE=20

df | grep '[0-9]%' | egrep 'sd|hd' | \
while read line 
do
# if [ `echo $line | awk -F" " '{ print $5 }' | cut -d% -f1` -gt "$USAGE_SPACE" ]; then
# echo "Disk space of `echo $line | awk -F" " '{ print $6}'` belongs to `hostname` is over $USAGE_SPACE%" | mail -s "HD DISK is not enough" $USER
# fi

set -- $line
if [ `echo $5 | cut -d% -f1` -gt $USAGE_SPACE ]; then
echo "Disk space of `echo $6` belongs to `hostname` is over $USAGE_SPACE%" | mail -s "HD DISK is not enough" $USER
fi
done

Remark的部份是小弟以前的做法,利用awk去filter出硬碟使用的百分比與目錄名稱,但拜讀了新書"Linux 網路安全管理與監控",學到了可透過set --$line方便取出某行的資料為引數使用,好用!


3 comments:

Unknown said...

超贊的set -- $VAR command

看來以後用awk的機會會少很多了


感謝分享

Unknown said...

btw,如果遇到有使用LVM的系統,會因為df指令的輸出會跳行而出問題。

建議改用df -T來避開。

Unknown said...

抱歉,說錯了,應該是用df -P來避開。