我试图让一个简单的 while 循环在使用两个条件的 bash 中工作,但是在尝试了各种论坛的许多不同语法之后,我无法停止抛出错误。这是我所拥有的:
while [ $stats -gt 300 ] -o [ $stats -eq 0 ]
我也试过:
while [[ $stats -gt 300 ] || [ $stats -eq 0 ]]
...以及其他几个构造。我希望这个循环继续 while$stats is > 300
或 if $stats = 0
。
我试图让一个简单的 while 循环在使用两个条件的 bash 中工作,但是在尝试了各种论坛的许多不同语法之后,我无法停止抛出错误。这是我所拥有的:
while [ $stats -gt 300 ] -o [ $stats -eq 0 ]
我也试过:
while [[ $stats -gt 300 ] || [ $stats -eq 0 ]]
...以及其他几个构造。我希望这个循环继续 while$stats is > 300
或 if $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 ))
一些注意事项:
引用内部的参数扩展[[ ... ]]
并且((...))
是可选的;如果未设置变量,-gt
则-eq
假定值为 0。
using$
在 inside 是可选的(( ... ))
,但使用它可以帮助避免意外错误。如果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 ]