首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在for或while循环中嵌套if for语句

在for或while循环中嵌套if for语句
EN

Stack Overflow用户
提问于 2017-10-18 19:35:43
回答 1查看 802关注 0票数 0

我对bash相当陌生,所以如果我的代码看起来不太好或者不正确,请放心。

我现在试着做一个脚本,它将平一个主机名,如果那个主机名没有响应,它将获取主机名的IP,并尝试它。似乎毫无意义,但我有自己的理由。

我遇到的问题是,我的脚本没有在脚本的末尾识别“已完成”。

代码语言:javascript
复制
#!/bin/bash
#while read hostname; do
for hostname in $(cat host.txt); do
ping -c1 $hostname 1>/dev/null 2>/dev/null
SUCCESS=$?
if [ $SUCCESS -eq 0 ]
        then
        echo "$hostname has replied"
else#[ $SUCCESS -ne 0 ]
        echo "Hostname didn't reply, trying IP"
        ip=`cat /etc/hosts | grep $hostname | awk '{print $1}' `
        ping -c1 $ip 1>/dev/null 2>/dev/null
        SUCCESS=$?
                if [ $SUCCESS -eq 0 ]
                        then
                        echo "$ip has replied"
                        echo "------------------------------"
                else
                        echo "$ip didn't reply"
                        echo "------------------------------"
                fi
done
EN

回答 1

Stack Overflow用户

发布于 2022-06-01 01:46:46

我对代码进行了重新格式化,以更标准和更通用的方式缩进代码。我还添加了一些可能有助于人们学习基础知识的评论,比如4年前的@Root_。你可以检查一下:

代码语言:javascript
复制
#!/bin/bash

# I just used an editor that can do formatting of code.
# I asked it to reindent all lines within my settings.
# There are several programs to do this. I used vim.

for hostname in $(cat host.txt); do

    ping -c1 $hostname 1>/dev/null 2>/dev/null
    SUCCESS=$?

    # ping ended successfully?
    if [ $SUCCESS -eq 0 ] then
        echo "$hostname has replied"
    else
        echo "Hostname didn't reply, trying IP"

        ip=`cat /etc/hosts | grep $hostname | awk '{print $1}' `

        ping -c1 $ip 1>/dev/null 2>/dev/null
        SUCCESS=$?

        # ping ended successfully?
        if [ $SUCCESS -eq 0 ] then
            echo "$ip has replied"
            echo "------------------------------"
        else
            echo "$ip didn't reply"
            echo "------------------------------"
        fi
    fi
    # You missed this last "fi". With good indentation,
    # we see it easily. And with an editor that is done
    # for developers, it may even point us a place to
    # look for errors. In this case, the "done" was
    # written in red, which helped me asking 2 questions:
    # 1. Is this done in the right place? Where is its
    # corresponding "do"? (it is on on line 7 now)
    # 2. So, if the done is correct, what else is wrong?
    # Then, for the indentation I did, it was easy to see
    # the 'if' on line 13 did not have a 'fi'.
done
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46817903

复制
相关文章

相似问题

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