英文:
Using shell, how to skip to next element in a for loop?
问题
这是我的脚本应该执行的操作:对导入的文本文件的每一行,它会对该行的IP地址进行5次ping测试。如果在5次中有3次无法连接到IP,它会输出"it's down!"并继续下一个IP... 除了我不知道如何配置这个"skip"部分。
以下是我的当前代码:
FILE=file.txt
unreachableIP=0
while IFS='' read -r line || [ -n "$line" ]; do
set -- $line
for (( i=1; i<=5; i++ ))
do
echo "Ping $1 $i times"
ping -c 1 $1
if [ "$?" = 0 ]
then
echo "reachable"
else
echo "unreachable"
((unreachableIP++))
echo $unreachableIP
if [ $unreachableIP -eq 3 ]
then
echo "it's down!"
unreachableIP=0
fi
fi
done
done < $FILE
示例:如果IP地址第一次可达,第二次不可达,第三次不可达,第四次不可达,我希望脚本能够移动到下一个IP(下一行),而不会尝试第五次ping。
这是"file.txt"的内容:
8.8.8.8 GoogleDNS
1.1.1.1 CloudFlareDNS
213.1.1.1 SomeFakeIPForDebug
谢谢你的帮助。
编辑:我不想使用break,因为它会停止ping其他的IP...我希望它只停止ping当前的IP。
英文:
Here's what my script should do: it pings 5 times the IP address of each line of an imported text file. If the IP is unreachable 3 of the 5 times, it echo "it's down!" and (should) move on to the next IP... Except I don't know how to configure this "skip" part.
Here is my current code:
FILE=file.txt
unreachableIP=0
while IFS='' read -r line || [ -n "$line" ]; do
set -- $line
for (( i=1; i<=5; i++ ))
do
echo "Ping $1 $i times"
ping -c 1 $1
if [ "$?" = 0 ]
then
echo "reachable"
else
echo "unreachable"
((unreachableIP++))
echo $unreachableIP
if [ $unreachableIP -eq 3 ]
then
echo "it's down!"
unreachableIP=0
fi
fi
done
done < $FILE
Example: if the IP address is reachable 1st time, unreachable 2nd time, unreachable 3rd time and unreachable 4th time, I want the script to move to the next IP (next line) and not try to ping a 5th time.
Here is the file.txt
:
8.8.8.8 GoogleDNS
1.1.1.1 CloudFlareDNS
213.1.1.1 SomeFakeIPForDebug
Thanks for your help.
EDIT: I don't want to use break because it will stop pinging the other IPs too... and I would like it to only stop pinging the current IP.
答案1
得分: 4
继续
>中断和继续的循环控制命令[1]与其他编程语言中的对应命令完全相同。中断命令终止循环(跳出循环),而继续命令导致跳转到循环的下一次迭代,跳过该特定循环周期中的所有剩余命令。
查看http://tldp.org/LDP/abs/html/loopcontrol.html
英文:
continue
>The break and continue loop control commands [1] correspond exactly to their >counterparts in other programming languages. The break command terminates the loop >(breaks out of it), while continue causes a jump to the next iteration of the loop, >skipping all the remaining commands in that particular loop cycle.
答案2
得分: 1
Use break
来实现你所说的"跳过"功能。
例如:
if [ "$unreachableIP" -eq 3 ]; then
break
fi
它将退出当前的循环。
英文:
Use break
to achieve the "skip" feature you're talking about.
For example
if [ "$unreachableIP" -eq 3 ]; then
break
fi
It will exit the current loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论