Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
bash脚本中for循环内的嵌套if语句_Bash_If Statement_For Loop_Nmap - Fatal编程技术网

bash脚本中for循环内的嵌套if语句

bash脚本中for循环内的嵌套if语句,bash,if-statement,for-loop,nmap,Bash,If Statement,For Loop,Nmap,我正在编写一个bash脚本,它经过一个for循环,该循环是每个主机名的列表,然后将测试每个主机是否在端口22上响应,如果是,则执行ssh会话,但是第一个和第二个if语句仅在列表中的第一个主机上执行,而不是在其余主机上执行。如果主机在端口22上没有响应,我希望脚本继续到下一个主机。如何确保脚本在列表中的每个主机上运行ssh?这应该是另一个for循环吗 #!/bin/bash hostlist=$(cat '/local/bin/bondcheck/hostlist_test.txt') fo

我正在编写一个bash脚本,它经过一个for循环,该循环是每个主机名的列表,然后将测试每个主机是否在端口22上响应,如果是,则执行ssh会话,但是第一个和第二个if语句仅在列表中的第一个主机上执行,而不是在其余主机上执行。如果主机在端口22上没有响应,我希望脚本继续到下一个主机。如何确保脚本在列表中的每个主机上运行ssh?这应该是另一个for循环吗

#!/bin/bash

hostlist=$(cat '/local/bin/bondcheck/hostlist_test.txt')


for host in $hostlist;  do

test=$(nmap $host -P0 -p 22 | egrep 'open|closed|filtered' | awk '{print $2}')

        if [[ $test = 'open' ]]; then

                        cd /local/bin/bondcheck/
                        mv active.current active.fixed
                        ssh -n $host echo -n "$host: ; cat /proc/net/bonding/bond0 | grep Active" >> active.current

                        result=$(comm -13 active.fixed active.current)

                if [ "$result" == "" ]; then
                                exit 0
                else
                        echo "$result" | cat -n
                fi

        else
                echo "$host is not responding"
        fi
done

退出0
退出整个脚本;您只想继续循环的下一个迭代。使用
继续

您的问题最有可能出现在下面的行中

if [ "$result" == "" ]
then
 exit 0
else
 echo "$result" | cat -n
fi
此处,当
$result
为空时,
退出0
会导致整个脚本退出。您可以使用以下方法:

if [ "$result" != "" ] #proceeding on non-empty 'result'
then
 echo "$result" | cat -n
fi

请注意,在nmap
-P0
的更高版本中,它与
-Pn
相同。此外,您的
测试=$(nmap$host-P0…
行可能会被
test=$(nmap$host-P0-p22 | awk'/^22\/tcp/{print$2}'替换为
,谢谢:)