繁体   English   中英

Bash脚本,while循环中的多个条件

[英]Bash scripting, multiple conditions in while loop

我正在尝试使用bash中的一个简单的while循环使用两个条件,但在尝试了各种论坛的许多不同语法之后,我无法停止抛出错误。 这是我有的:

while [ $stats -gt 300 ] -o [ $stats -eq 0 ]

我也尝试过:

while [[ $stats -gt 300 ] || [ $stats -eq 0 ]]

......以及其他几个结构。 我希望这个循环继续,而$stats is > 300或者如果$stats = 0

正确的选项是(按推荐顺序递增):

# 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 ))

一些说明:

  1. 引用[[ ... ]]((...))内的参数扩展是可选的; 如果未设置变量,则-gt-eq将采用值0。

  2. (( ... ))使用$是可选的,但使用它可以帮助避免无意的错误。 如果未设置stats ,则(( stats > 300 ))将假设stats == 0 ,但(( $stats > 300 ))将产生语法错误。

尝试:

while [ $stats -gt 300 -o $stats -eq 0 ]

[是一个test电话。 它不仅仅用于分组,就像其他语言中的括号一样。 检查man [man test以获取更多信息。

第二种语法外部的额外[]是不必要的,并且可能令人困惑。 您可以使用它们,但如果必须,则需要在它们之间使用空格。

或者:

while [ $stats -gt 300 ] || [ $stats -eq 0 ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM