2016-11-14 28 views
1

下面的bash腳本輸出「ERROR!」而不是「服務器錯誤響應」,即使wget的回報8:由bash腳本中的比較運算符設置的退出狀態

#!/bin/bash 

wget -q "www.google.com/unknown.html" 
if [ $? -eq 0 ] 
then 
    echo "Fetch successful!" 
elif [ $? -eq 8 ] 
then 
    echo "Server error response" 
else 
    echo "ERROR!" 
fi 

當腳本以上與-x運行,0的第一比較似乎退出狀態被設置爲1:

+ wget www.google.com/unknown.html 
+ '[' 8 -eq 0 ']' 
+ '[' 1 -eq 8 ']' 
+ echo 'ERROR!' 
ERROR! 

我通過使用一個用於存儲wget退出狀態的變量解決了這個問題,但是我找不到任何有關$的各種方法的參考。已設置。擊細節:

$ bash --version 
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) 
Copyright (C) 2013 Free Software Foundation, Inc. 
License GPLv3+: GNU GPL version 3 or later 
<http://gnu.org/licenses/gpl.html> 

This is free software; you are free to change and redistribute it. 
There is NO WARRANTY, to the extent permitted by law. 

可能有人點我一個?

+0

'man wget |更少+/EXIT'? – Cyrus

回答

3

$?解釋,雖然很短暫,在特殊參數的man bash參數部分:

?  Expands to the exit status of the most recently executed fore- 
      ground pipeline. 

@chepner把它最好在他的評論:

的關鍵需要了解的是,每個[ ... ]都是獨立的前臺管道,不是if語句語法的一部分,並且它們按順序執行,隨着時間的推移更新$?

如果你想使用的if-else鏈,然後保存在一個變量的$?的價值,並在該變量使用條件:

wget -q "www.google.com/unknown.html" 
x=$? 
if [ $x -eq 0 ] 
then 
    echo "Fetch successful!" 
elif [ $x -eq 8 ] 
then 
    echo "Server error response" 
else 
    echo "ERROR!" 
fi 

但在這個例子中,case會更實用:

wget -q "www.google.com/unknown.html" 
case $? in 
    0) 
     echo "Fetch successful!" ;; 
    8) 
     echo "Server error response" ;; 
    *) 
     echo "ERROR!" 
esac 
+1

要理解的關鍵是每個''''是一個單獨的前臺流水線,而不是'if'語句的語法的一部分,並且它們按順序執行,隨着時間的推移更新'$?'。 – chepner

+0

精美的,謝謝@chepner! – janos

+0

@chepner,謝謝! if條件是否是「管道」的參考?你從哪裏瞭解到的? – swoop81

0

嘗試在$上使用開關盒?或存儲$?在一個變量中。

+0

謝謝,我知道如何解決問題(請參閱我原來的問題)。我只是想要一個手冊頁或參考資料,以上述的@chepner的說法來說明if條件是他們自己的前臺流水線。 – swoop81