我需要一個 bash 腳本來檢查互聯網連接。我先用了下面的。
#!/bin/bash
#
while true; do
if ping -c 1 1.1.1.1 &> /dev/null
then
echo "internet working"
else
echo "no internet"
fi
sleep 5
done
它作業正常,但有時會失敗。所以我一直在尋找可以對多個 IP 進行 ping 測驗的東西,這樣只有一個 IP 必須成功 ping 才能假設連接。我對 bash 非常陌生,因此對任何錯誤表示歉意。
如何更正以下腳本以使其按預期作業?
#!/bin/bash
#
while true; do
count= '0'
if ping -c 1 1.1.1.1 &> /dev/null
then
count= '1'
fi
if ping -c 1 8.8.8.8 &> /dev/null
then
count= count '1'
fi
if ping -c 1 www.google.com &> /dev/null
then
count= count '1'
fi
if [ count -lt 1 ]
then
echo "no internet"
else
echo "internet working"
fi
sleep 5
done
uj5u.com熱心網友回復:
在 if 陳述句中鏈接命令:
if ping -c 1 1.1.1.1 || ping -c 1 8.8.8.8 || ping -c 1 www.google.com
then
echo "One of the above worked"
else
echo "None of the above worked" >&2
fi
如果需要,那么您仍然可以重定向ping命令的輸出。
if ping ... > /dev/null # redirect stdout
if ping ... 2> /dev/null # redirect stderr
if ping ... &> /dev/null # redirect both (but not POSIX) `>/dev/null 2>&1` is though.
uj5u.com熱心網友回復:
我會為此任務使用一個函式,以便我可以將要 ping 的主機作為引數傳遞:
#!/bin/bash
# Check internet connectivity
# Returns true if ping succeeds for any argument. Returns false otherwise
ckintconn () {
for host
do
ping -c1 "$host" && return
done
return 1
} &>/dev/null
if ckintconn 1.1.1.1 8.8.8.8 www.google.com
then
echo "internet working"
else
echo "no internet"
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417463.html
標籤:
