65

2 つの条件を使用する単純な while ループを bash で動作させようとしていますが、さまざまなフォーラムから多くの異なる構文を試した後、エラーのスローを止めることはできません。ここに私が持っているものがあります:

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

私も試しました:

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

... および他のいくつかの構成要素。このループを続けたい while$stats is > 300または if $stats = 0.

4

3 に答える 3

146

正しいオプションは次のとおりです(推奨の昇順)。

# 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. 内部のパラメータ展開を引用すること[[ ... ]]((...))オプションです。変数が設定されていない場合、値は0になります-gt-eq

  2. $内部での使用はオプションですが(( ... ))、使用すると意図しないエラーを回避するのに役立ちます。statsが設定されていない場合、は(( stats > 300 ))と見なされますが、構文エラーが発生しますstats == 0(( $stats > 300 ))

于 2013-03-20T22:10:20.377 に答える
2

試す:

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

[への呼び出しtestです。他の言語の括弧のように、グループ化だけではありません。man [詳細については、 またはを確認man testしてください。

于 2013-03-20T21:04:27.307 に答える
0

2 番目の構文の外側にある余分な [ ] は不要であり、混乱を招く可能性があります。それらを使用することもできますが、必要な場合はそれらの間に空白を入れる必要があります。

または:

while [ $stats -gt 300 ] || [ $stats -eq 0 ]
于 2013-03-20T21:14:07.623 に答える