bash计时器的实现案例:检查并记录网络稳定性的脚本

bash的帮助中提到SECONDS系统变量:

SECONDS Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

我们在程序执行期间,检查这个变量,即可实现记时的功能。

本例是用来每隔一个固定时间,ping一个IP,出现故障时记录下来的脚本。

#!/bin/bash#set-oerrexitexportSCRIPT=$0SID=$PPIDusage(){echo-e”Usage:”echo-e”\tbash$0[OPTs]”echo-e”\t-W|–timeout\t\t<M>”echo-e”\t-I|–interval\t\t<N>”echo-e”\t-i|–ip\t\t\t<A.B.C.D>”echo-e”\t-L|–level\t\t<info|error>”echo-e”\t-l|–log\t\t</tmp/${SCRIPT}-${SID}.log>”echo-e”\t-h\t\t\tPrintthisinfo”echo-e”Example:”echo-e”\tbash$0-W1-I3-i127.0.0.1-Lerror-log/tmp/${SCRIPT}-${SID}.log”echo-e”\tbash$0″exit255}[$#-eq4]&&usage#默认参数LOGFILE=”/tmp/${SCRIPT}-${SID}.log”touch$LOGFILETIMEOUT=1INTERVAL=10LEVEL=infoIP=127.0.0.1MyIP=$(ipaddrsheth0|awk’/^[\]*inet/{split($2,IP,”http://wangxiaoyu.blog.51cto.com/”);printfIP[1]}’)#参数获取TEMP=$(getopt-oW:I:i:L:l:h–longtimeout:,interval:,ip:,level:,log:,help–“$@”)[$?!=0]&&usageevalset–“$TEMP”#参数处理whiletrue;docase”$1″in-W|–timeout)TIMEOUT=$2;shift2;;-I|–interval)INTERVAL=$2;shift2;;-i|–ip)IP=$2;shift2;;-L|–level)LEVEL=$2;shift2;;-l|–log)LOGFILE=$2;shift2;;-h|–help)usage;shift;;–)shift;break;;esacdone[“$IP”=””]&&usageadjust(){return$((SECONDS%INTERVAL))}pinger(){ping$1-W$TIMEOUT-c1|tail-1|awk-F/'{print$(NF-1)}’2>/dev/null}logger(){echo-e”$(date+%F””%T)\t””$@”}trapper(){trap”logger\”EXIT($SID)\t$MyIP->$IP\”>>$LOGFILE&&exit0″12915}trapperlogger”START($SID)\t$MyIP->$IP”>>$LOGFILEwhiletruedoifadjust;thenunsettt=$(pinger$IP)if[“$t”=””];thenlogger”ERROR($SID)\t$MyIP->$IP${TIMEOUT}(S)”>>$LOGFILE&else[“$LEVEL”=”erorr”]||logger”INFO($SID)\t$MyIP->$IP${t}(ms)”>>$LOGFILE&fisleep1fisleep0.1done

执行

bash pinger.sh -W 1 -I 2 -i a.b.c &

执行结果如下:

# tail -f -n 10 /tmp/bash-26729.log

2015-04-28 17:24:50START(26729)192.168.202.2 -> a.b.c

2015-04-28 17:24:50INFO(26729)192.168.202.2 -> a.b.c 0.630(ms)

2015-04-28 17:24:52INFO(26729)192.168.202.2 -> a.b.c 0.575(ms)

2015-04-28 17:24:54INFO(26729)192.168.202.2 -> a.b.c 0.875(ms)

本文出自 “希奥开源” 博客,,请务必保留此出处

当你见过了世界上最美丽的风景,

bash计时器的实现案例:检查并记录网络稳定性的脚本

相关文章:

你感兴趣的文章:

标签云: