Test ip is able to ping, but only one loop it ende

2019-09-04 03:48发布

If i wants to enter a ip to ping, if it is able to ping, i wish to enter a difference ip. How am i going to change the script? Look at my script, if i enter ip 192.168.0.1 is able to ping, i wants to enter a different ip. HOw am i going to add.

echo "==============Ping IP=============="
echo -n "Please enter ip to ping 192.168.0."
read ipaddress
Addip=192.168.0.$bmcipaddress
echo "================================"
echo "IP Add: $Addip"
ping -c 1 $Addip >"pinglog"
ping_ok=`cat "pinglog"| grep Unreachable`
echo "======="


if [ "$ping_ok" == "" ]; then
        echo $bmcip "==>ping PASS"
else
        echo $bmcip "==>ping BMC FAIL"



fi

标签: linux bash
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-04 04:18

Try this.

while read -p "Please enter ip to ping 192.168.0." ipaddress; do
    bmcip="192.168.0.$ipaddress"
    if ping -c 1 "$bmcip" >/dev/null; then
        status="PASS"
    else
        status"FAIL"
    fi
    echo "$bmcip ==>ping $status"
done

The read command will fail at end of file, so you can easily terminate the script with ctrl-D (as well as, of course, ctrl-C). You could easily extend it to also exit on empty input.

The exit status from ping indicates whether or not it succeeded, so this catches more error scenarios than just "Unreachable". In general, shell tools return an exit status precisely in order to use this sort of conditional construct to see whether or not a command succeeded, and you should avoid hard-coding output strings if you can (they could be localized, change between versions, etc).

If you want to minimize this further, you could squeeze it down to

while read -p "Please enter ip to ping 192.168.0." ipaddress; do
    Addip="192.168.0.$ipaddress"
    echo -n "$bmcip ==>ping "
    ping -c 1 "$Addip" >/dev/null && echo "PASS" || echo "FAIL"
done

Since you are not using the log file for anything outside of your script, I assume it's an unnecessary temporary file which we are better off not creating. If you need it for diagnostics, maybe you should not overwrite it.

查看更多
登录 后发表回答