bash脚本编程,在while循环多个条件 [英] Bash scripting, multiple conditions in while loop
问题描述
我想while循环使用两个条件的bash工作,得到一个简单的,但是从各种论坛尝试许多不同的语法后,我不能停止抛出一个错误。以下是我有:
I'm trying to get a simple while loop working in bash that uses two conditions, but after trying many different syntax from various forums, I can't stop throwing an error. Here is what I have:
while [ $stats -gt 300 ] -o [ $stats -eq 0 ]
我也尝试:
while [[ $stats -gt 300 ] || [ $stats -eq 0 ]]
...以及其他几个构造。我想这个循环继续,而 $统计是> 300
或者 $统计= 0
。
推荐答案
正确的选项是(增加推荐的顺序排列):
The correct options are (in increasing order of recommendation):
# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]
# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]
# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]
# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]
# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))
# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))
一些注意事项:
-
引用在
的参数扩展[...]]
和((...))
是可选的;如果变量没有设置,-gt
和-eq
将假定值0。
Quoting the parameter expansions inside
[[ ... ]]
and((...))
is optional; if the variable is not set,-gt
and-eq
will assume a value of 0.
使用 $
在里面可选的((...))
,但使用它可以帮助避免无意识的错误。如果统计
没有设置,那么((统计> 300))
将承担统计== 0
,但(($统计高于300))。
将产生一个语法错误
Using $
is optional inside (( ... ))
, but using it can help avoid unintentional errors. If stats
isn't set, then (( stats > 300 ))
will assume stats == 0
, but (( $stats > 300 ))
will produce a syntax error.
这篇关于bash脚本编程,在while循环多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!