所有响应时Ping服务器并执行命令

时间:2016-03-16 10:50:56

标签: bash ping

我有以下脚本:

#!/bin/bash

servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )

for i in "${servers[@]}";
do
ping -c 4 "$i" >/dev/null 2>&1 &&
echo "Ping Status of $i : Success" ||
echo "Ping Status of $i : Failed"
done

输出

Ping Status of 10.10.10.1 : Success
Ping Status of 10.10.10.2 : Success
Ping Status of 10.10.10.3 : Failed
Ping Status of 10.10.10.4 : Failed

我需要不断ping那些地址,直到它们全部成功,然后执行一个命令。我不需要输出成功/失败,我只想ping所有IP,然后回复#34;所有主机在线",例如。

1 个答案:

答案 0 :(得分:1)

我希望代码中的注释能够清楚地说明这一点。基本上,诀窍是将整个事物包装在无限while循环中,并使用变量来表示其中一个命令是否失败。

#!/bin/bash

servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )

# Keep looping forever : is a special builtin command that does
# nothing and always exits with code 0
while :; do
    # Assume success
    failed=0

    # Loop over all the servers
    for i in "${servers[@]}"; do
        # We failed one!
        if ! ping -c 4 "$i" >/dev/null 2>&1; then
            # Set failed to 1 to signal the code after the for loop that
            # a ping failed
            failed=1

             # We don't need to ping the others, so we can break from this for
             # loop
             break
        fi
    done

    # If none of the ping commands failed, the $failed variable is still 0
    if [ $failed -eq 0 ]; then
        # Yes! We can now run our command
        echo "All hosts online"

        # And break the infinite while loop
        break
    else
        # Nope, wait a while and start the loop from the top
        sleep 5
    fi
done

我还修了一个错字;您使用了/dev/nul,但应该是/dev/null,其中有两个l