shell指令碼——實現延時大於10ms列印輸出
阿新 • • 發佈:2021-02-19
技術標籤:shell
一、程式碼展示
#!/bin/bash
ip=$*
echo $ip
num=`ping -c 3 ${ip}|grep icmp_seq|awk '{print $7}'|cut -d= -f2`
for snum in $num
do
if [ `echo "${snum}>10"|bc` -eq 1 ];
then
echo "延時大於10ms,現在為${snum}";
fi
done
二、程式碼解析
變數賦值
#$* 是以一個單字串顯示所有向指令碼傳遞的引數,把引數值賦給變數ip
ip=$*
核心程式碼
num=`ping -c 10 ${ip}|grep icmp_seq|awk '{print $7}'|cut -d= -f2`
#ping命令執行3次 ping -c 3 ${ip} 此時結果: PING www.a.shifen.com (110.242.68.4): 56 data bytes 64 bytes from 110.242.68.4: icmp_seq=0 ttl=49 time=12.490 ms 64 bytes from 110.242.68.4: icmp_seq=1 ttl=49 time=12.712 ms 64 bytes from 110.242.68.4: icmp_seq=2 ttl=49 time=13.172 ms --- www.a.shifen.com ping statistics --- 3 packets transmitted, 3 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 12.490/12.791/13.172/0.284 ms
#管道命令搜尋包含icmp_seq的行
grep icmp_seq
執行ping -c 3 www.baidu.com | grep icmp_seq結果:
64 bytes from 110.242.68.4: icmp_seq=0 ttl=49 time=28.042 ms
64 bytes from 110.242.68.4: icmp_seq=1 ttl=49 time=12.626 ms
64 bytes from 110.242.68.4: icmp_seq=2 ttl=49 time=12.468 ms
#一行一行的讀取指定的檔案, 以空格作為分隔符,列印第7個欄位 awk '{print $7}' 執行ping -c 3 www.baidu.com | grep icmp_seq | awk '{print $7}'結果: time=13.738 time=13.246 time=13.370 #等號分割的兩端字串,選後一部分 cut -d '=' -f 2 執行:ping -c 3 www.baidu.com | grep icmp_seq | awk '{print $7}' | cut -d '=' -f 2: 20.684 20.841 17.836
迴圈遍歷
for snum in $num
do
#-eq 1用來判斷echo命令的輸出是否為1,為1則說明為true
if [ `echo "${snum}>10"|bc` -eq 1 ];
then
echo "延時大於10ms,現在為${snum}";
fi
done