首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当所有响应时,Ping服务器和执行命令

当所有响应时,Ping服务器和执行命令
EN

Stack Overflow用户
提问于 2016-03-16 10:50:55
回答 1查看 461关注 0票数 0

我有以下脚本:

代码语言:javascript
复制
#!/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

哪种输出

代码语言:javascript
复制
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

我需要不断地点击这些地址,直到它们都成功,然后执行一个命令。我不需要成功/失败的输出,我只是想要平所有的IP,然后回应“所有主机在线”,例如。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-16 10:55:30

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

代码语言:javascript
复制
#!/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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36033484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档