爱程序网

监控文件系统示例脚本

来源: 阅读:

[root@localhost shell]# cat monitor_disk.sh 
#!/bin/bash

#This script is used to monitor disk.
#2013/12/17

function disk_speed()
{
        A=`df -k | grep "$1" | awk '{print $3}'`
        sleep 30
        B=`df -k | grep "$1" | awk '{print $3}'`
        D=`expr $B - $A`
        SPEED=`expr $D / 30`
        echo $SPEED
        unset A B D SPEED
}

function avai_time()
{
        FREE=`df -k | grep "$1" | awk '{print $4}'`
        if TIME=`expr $FREE / $2`
        then
                if [ $TIME -ge 60 ]
                then
                        A=`expr $TIME / 60`
                        echo $A" minutes"
                        unset FREE TIME
                        return 0
                else
                        echo "Unkow"
                        unset FREE TIME
                        return 0
                fi
        else
                echo "Unknow"
                unset FREE TIME
                return 1
        fi
}

function content()
{
        TEMP_FILE=/root/disk_monitor.tmp
        echo "Warning disk:"$1 >$TEMP_FILE
        echo "Used space:"$2 >>$TEMP_FILE
        echo "Available space:"$3 >>$TEMP_FILE
        echo "Use%:"$4"%" >>$TEMP_FILE
        echo "Write speed:"$5 >>$TEMP_FILE
        echo "Estimated time remaining:"$6 >>$TEMP_FILE
        echo "Now time:"`date +"%Y-%m-%d %H:%M"` >>$TEMP_FILE
        unset TEMP_FILE
        return 0
}

MON_DISK=/dev/md0
USED=`df -h | grep "$MON_DISK" | awk '{print $5}' | sed 's/%//'`

if [ $USED -ge 90 ]
then
        USED_SPACE=`df -h | grep "$MON_DISK" | awk '{print $4}'`
        AVAI_SPACE=`df -h | grep "$MON_DISK" | awk '{print $3}'`
        W_SPEED=`disk_speed $MON_DISK`
        if [ $W_SPEED != 0 ]
        then
                S_TIME=`avai_time $MON_DISK $W_SPEED`
        else
                S_TIME="Unknow"
        fi
        content $MON_DISK $USED_SPACE $AVAI_SPACE $USED $W_SPEED $S_TIME
        mail -s "Disk warning" root </root/disk_monitor.tmp
        rm -rf /root/disk_monitor.tmp
        unset MON_DISK USED USED_SPACE AVAI_SPACE W_SPEED S_TIME
fi

[root@localhost shell]# ./monitor_disk.sh 
./monitor_disk.sh: line 57: [: -ge: unary operator expected

运行时出现上面的错误:

http://blog.csdn.net/goodlixueyong/article/details/6564591

针对本例(测试中是数值比较)的解决方案:

if [ $USED -ge 90 ]---> if [[ $USED -ge 90 ]]

修改后成功运行:

[root@localhost shell]# ./monitor_disk.sh 
[root@localhost shell]#

如果测试中是字符串比较,那么除了上面的解决方案外,还有另外的解决办法:

if [ $STATUS = OK ]--->if [ “$STATUS” = OK ]

详细解释,请参看《shell13问》中的第10问。

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助