2013-03-20 80 views
35

我想獲得一個簡單的while循環在使用兩個條件的bash中工作,但在嘗試了來自各種論壇的許多不同語法後,我無法停止拋出錯誤。以下是我有:Bash腳本,在while循環中的多個條件

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

我也曾嘗試:

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

...以及其他幾個人結構。我想要這個循環繼續,而$stats is > 300$stats = 0

回答

81

正確的選項是(增加推薦的順序排列):

# 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.1

  2. 使用$裏面((...))可選的值,但使用它可以幫助避免無意的錯誤。如果stats未設置,則((stats > 300))將假定爲stats == 0,但(($stats > 300))將產生語法錯誤。

+0

夢幻般的答案,令人驚訝的徹底 – jake9115 2013-03-21 14:49:54

+0

布拉沃。回答帖子的經典方式。做得好。我假設你可以使用'until'的相同語法,是嗎? – SaxDaddy 2014-08-14 21:05:57

+0

@SaxDaddy或多或少,只要你注意正確否定條件:'while [foo -o bar]'變成'直到! [foo -o bar]',但'while foo ||酒吧'成爲'直到! foo &&! bar'。 – chepner 2014-08-14 21:19:16

1

嘗試:

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

[test通話。它不僅僅是用於分組,就像其他語言的括號一樣。請查詢man [man test瞭解更多信息。

+1

我推薦'[''over'['。看到我對其他答案的評論。 – danfuzz 2013-03-20 21:50:59

+0

這很公平。我使用[],因爲這是OP試圖使用的。我已經看到兩個成功。 – drewmm 2013-03-20 21:59:45

0

第二種語法外部的extra []是不必要的,並且可能會引起混淆。你可以使用它們,但是如果你必須有它們之間的空白。

或者:

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

實際上''[''通常是引入測試表達式的首選內置函數。它比舊的單一'['語法有幾個優點。 – danfuzz 2013-03-20 21:49:52