bash 脚本中 for 循环内的嵌套 if 语句
Nested if statement inside a for loop in bash script
我正在编写一个 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 }')
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
exit 0
退出整个脚本;您只想继续循环的下一次迭代。请改用 continue
。
你的问题最有可能在行
if [ "$result" == "" ]
then
exit 0
else
echo "$result" | cat -n
fi
此处 exit 0
导致整个脚本在 $result
为空时退出。您可以使用 :
if [ "$result" != "" ] #proceeding on non-empty 'result'
then
echo "$result" | cat -n
fi
我正在编写一个 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 }')
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
exit 0
退出整个脚本;您只想继续循环的下一次迭代。请改用 continue
。
你的问题最有可能在行
if [ "$result" == "" ]
then
exit 0
else
echo "$result" | cat -n
fi
此处 exit 0
导致整个脚本在 $result
为空时退出。您可以使用 :
if [ "$result" != "" ] #proceeding on non-empty 'result'
then
echo "$result" | cat -n
fi