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

我试图得到一个简单的while循环在bash中使用两个条件,但在尝试从各种论坛的许多不同的语法后,我不能停止抛出一个错误。 这是我有什么:

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. [[ ... ]]((...))引用参数扩展是可选的; 如果variables没有设置, -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 ]