[英]Bash scripting, multiple conditions in while loop
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. 我正在尝试使用bash中的一个简单的while循环使用两个条件,但在尝试了各种论坛的许多不同语法之后,我无法停止抛出错误。 Here is what I have:
这是我有的:
while [ $stats -gt 300 ] -o [ $stats -eq 0 ]
I have also tried: 我也尝试过:
while [[ $stats -gt 300 ] || [ $stats -eq 0 ]]
... as well as several others constructs. ......以及其他几个结构。 I want this loop to continue while
$stats is > 300
or if $stats = 0
. 我希望这个循环继续,而
$stats is > 300
或者如果$stats = 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 ))
Some notes: 一些说明:
Quoting the parameter expansions inside [[ ... ]]
and ((...))
is optional; 引用
[[ ... ]]
和((...))
内的参数扩展是可选的; if the variable is not set, -gt
and -eq
will assume a value of 0. 如果未设置变量,则
-gt
和-eq
将采用值0。
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. 如果未设置
stats
,则(( stats > 300 ))
将假设stats == 0
,但(( $stats > 300 ))
将产生语法错误。
Try: 尝试:
while [ $stats -gt 300 -o $stats -eq 0 ]
[
is a call to test
. [
是一个test
电话。 It is not just for grouping, like parentheses in other languages. 它不仅仅用于分组,就像其他语言中的括号一样。 Check
man [
or man test
for more information. 检查
man [
或man test
以获取更多信息。
The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. 第二种语法外部的额外[]是不必要的,并且可能令人困惑。 You may use them, but if you must you need to have whitespace between them.
您可以使用它们,但如果必须,则需要在它们之间使用空格。
Alternatively: 或者:
while [ $stats -gt 300 ] || [ $stats -eq 0 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.