将 bash while 循环限制为 10 次重试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27190963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit bash while loop to 10 retries
提问by fredrik
How can this while loop be limited to maximum 10 retries?
这个while循环如何限制为最多10次重试?
#!/bin/sh
while ! test -d /somemount/share/folder
do
echo "Waiting for mount /somemount/share/folder..."
sleep 1
done
回答by anubhava
Keep a counter:
保留一个计数器:
#!/bin/sh
while ! test -d /somemount/share/folder
do
echo "Waiting for mount /somemount/share/folder..."
((c++)) && ((c==10)) && break
sleep 1
done
回答by choroba
You can also use a for
loop and exit it on success:
您还可以使用for
循环并在成功时退出:
for try in {1..10} ; do
[[ -d /somemount/share/folder ]] && break
done
The problem (which exists in the other solutions, too) is that once the loop ends, you don't know how it ended - was the directory found, or was the counter exhausted?
问题(也存在于其他解决方案中)是,一旦循环结束,您不知道它是如何结束的 - 是找到目录,还是计数器耗尽?
回答by Jan K.
I would comment but I do not have enough points for that. I want to contribute anyway. So this makes it work even if the while loop is nested in another loop. before the break the c variable is being reset to zero. credits to @anubhava who came up with the original solution.
我会发表评论,但我没有足够的分数。无论如何我都想贡献。因此,即使 while 循环嵌套在另一个循环中,它也能正常工作。在中断之前,c 变量被重置为零。感谢提出原始解决方案的@anubhava。
#!/bin/sh
while ! test -d /somemount/share/folder
do
echo "Waiting for mount /somemount/share/folder..."
((c++)) && ((c==10)) && c=0 && break
sleep 1
done
回答by Noam Manos
You can use until
(instead of "while ! ... break), with a counter limit:
您可以使用until
(而不是“ while ! ... break),并带有计数器限制:
COUNT=0
ATTEMPTS=10
until [[ -d /somemount/share/folder ]] || [[ $COUNT -eq $ATTEMPTS ]]; do
echo -e "$(( COUNT++ ))... \c"
sleep 1
done
[[ $COUNT -eq $ATTEMPTS ]] && echo "Could not access mount" && (exit 1)
Notes:
笔记:
- Just like setting counter as variable, you can set var
condition="[[ .. ]]"
, and useuntil eval $condition
to make it more generic. echo $(( COUNT++ )) increases the counter while printing.
If running inside a function, use "return 1" instead of "exit 1".
- 就像将 counter 设置为变量一样,您可以设置 var
condition="[[ .. ]]"
,并使用until eval $condition
它来使其更通用。 echo $(( COUNT++ )) 在打印时增加计数器。
如果在函数内部运行,请使用“return 1”而不是“exit 1”。