簡體   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