Ping 测试 If-else 情况

Ping Test If-else case

我想在 Shell 脚本中基于 ping 测试显示“Unit 1 在线”或“Unit 1 离线”。但是,我找不到标志或方法来从 ping 测试的输出中提取文本,以便将其与 if-case 语句一起使用以获得所需的输出。

    read -p "Enter the number of Units: " x
    for ((i=1; i<=$x; i++))
    do
        ping -c1 a.b.c."$i"
        if ping=success
            echo "Unit "$i" is online"
        else
            echo "Unit "$i" is offline"
        fi
    done

如果您使用的是标准 GNU/Linux ping 工具,则 the manual states:

If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.

这意味着您可以从 shell 中的命令捕获退出代码并打开它。对于 bash:

if ping -c1 192.168.1."$i" ; then
    echo "Unit ${i} is online"
else
    echo "Unit ${i} is offline"
fi

或使用 ||&& 作为单行:

ping -c 192.168.1."$i" && echo "Unit ${i} is online" || echo "Unit ${i} is offline"