带有 IF ELSE 语句的 BASH Shell 无限循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8001094/
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
BASH Shell Infinite loop with IF ELSE Statment
提问by bikerben
Ok I know I've asked a similar question, I understand how to do an infinate loop:
好的,我知道我问过类似的问题,我了解如何进行无限循环:
while [ 1 ]
do
foo
bar
then
sleep 10
done
But if I want to run some (quite a few) IF ELSE Statements in this loop how would I get the script to carry on looping once they had completed how would I go about this?
但是,如果我想在这个循环中运行一些(相当多)IF ELSE 语句,一旦它们完成,我将如何让脚本继续循环,我将如何处理?
回答by Jan Hudec
while :; do
if cond1; then
whatever
elif cond2; then
something else
else
break
fi
done
- You do infinite loop using
while trueor using true's shorter alias:.[ 1 ]is needlessly complicated and is not what you think it is ([ 0 ]is also true!). Remember, the condition inifandwhileis arbitrary command whose exit status (zero = true, nonzero = false) is used as the condition value and[is just alias for specialtestcommand (both built-in in most shells, but they don't have to be). - Any shell construct is allowed between
do/doneincluding conditionals, more loops and cases. - Use
breakto terminate innermost loop from inside (just like most other languages).
- 您可以使用
while true或使用 true 较短的 alias进行无限循环:。[ 1 ]是不必要的复杂,不是您认为的那样([ 0 ]也是如此!)。请记住,ifand 中的条件while是任意命令,其退出状态(零 = 真,非零 = 假)用作条件值,[并且只是特殊test命令的别名(在大多数 shell 中都内置,但它们不必是)。 - 允许在
do/done包括条件、更多循环和案例之间使用任何 shell 构造。 - 用于
break从内部终止最内层循环(就像大多数其他语言一样)。
回答by chown
An if in bash is just: if [ some test ]; then some_command; fi:
bash 中的 if 只是if [ some test ]; then some_command; fi:
while [ 1 ]
do
? ? if [ some test ]
then
some command
else
other cmd
fi
sleep 10
done
回答by mudrii
Correction to chown case added brake to finish the loop Corrected
修正 chown case 添加刹车以完成循环修正
while [ 1 ]
do
if [ some test ]
then
some command
brake
else
other cmd
fi
sleep 10
done

