2011-11-23 50 views
15

好吧,實際上這是腳本的樣子:Bash中使用「和」 while循環

echo -n "Guess my number: " 
read guess 

while [ $guess != 5 ]; do 
echo Your answer is $guess. This is incorrect. Please try again. 
echo -n "What is your guess? " 
read guess 
done 

echo "That's correct! The answer was $guess!" 

我想改變的是這一行:

while [ $guess != 5 ]; do 

爲了這樣的事情:

while [ $guess != 5 and $guess != 10 ]; do 

在Java中,我知道「和」是「& &」,但似乎並沒有工作ħ ERE。我是用正確的方式來使用while循環嗎?

編輯:更新的問題,使其在搜索更加有用..

+0

JFYI代碼不正確:應該有'讀guess',不'$讀guess'。 –

+0

感謝您發現錯字:) – Smitty

回答

16

[]運營商在bash是到test一個電話,這是在man test記錄語法糖。 「或」由綴-o表達,但你需要一個「和」:

while [ $guess != 5 -a $guess != 10 ]; do 
+0

是的,我的錯誤「和」是我應該使用的。這可以解釋爲什麼「-o」在我早些時候嘗試時不起作用;我只是認爲它只適用於if語句,因爲它給了我一個錯誤。非常感謝您的及時回覆! – Smitty

+0

注意:這不是POSIX,因此不便攜。 –

30

有達到你想要的2分正確的和便攜式的方式。
好老shell語法:

while [ "$guess" != 5 ] && [ "$guess" != 10 ]; do 

而且bash語法(如指定):

while [[ "$guess" != 5 && "$guess" != 10 ]]; do 
+0

感謝您抽出時間讓我知道,我注意到現在我沒有將這兩個陳述歸爲一類,這就是爲什麼它不起作用。 – Smitty

1

的便攜和可靠的方法是使用case語句。如果你不習慣它,可能只需要圍繞語法來考慮一下。

while true; do 
    case $guess in 5 | 10) break ;; esac 
    echo Your answer is $guess. This is incorrect. Please try again. 
    echo -n "What is your guess? " 
    read guess # not $guess 
done 

我以前while true,但你實際上可以直接使用case聲明那裏。儘管如此,閱讀和維護會變得多毛。

while case $guess in 5 | 10) false;; *) true;; esac; do ... 
+0

感謝您花時間回答!當我在我的* nix上時,我會看看這個,但接下來:) – Smitty