比較 FreeBSD sh 中的 ping 時間

比較 FreeBSD sh 中的 ping 時間

如何從 ping 返回中去除時間?例如:

64 bytes from 10.3.0.1: icmp_seq=0 ttl=63 time=2.610 ms

我想獲取之後的值time=並將其傳遞給以下測試:

if time>=50.0; then do_something; fi

答案1

因此,如果您只想獲取time不帶ms標籤的值:

HOST="127.0.0.1"
PING_MS=`ping -c1 "$HOST" | /usr/bin/awk 'BEGIN { FS="=" } /time=/{gsub(/ ms/, ""); print $NF; exit}'`

這給了我:

0.058

現在,如果我們想測試 if time>=50.0,我們awk也可以使用它,因為 POSIXsh本身無法比較十進位數:

if echo $PING_MS | awk '{exit $1>=50.0?0:1}'; then
    echo "Ping time is >= 50.0ms."
fi

您可以將其縮短為:

if ping -c1 "$HOST" | /usr/bin/awk 'BEGIN { FS="=" } /time=/{gsub(/ ms/, ""); exit $NF>=50.0?0:1}'; then
    echo "Ping time is >= 50.0ms."
fi

FS是字段分隔符,並且$NF始終是最後一個字段。如果最後一個欄位是;$NF>=50.0?0:1將退出並顯示成功退出代碼>=50.0如果沒有,則傳回錯誤退出代碼。/time=/僅匹配包含time=.從字串中gsub(/ ms/, "");刪除。" ms"

相關內容