2014-10-20 31 views
71

條件我是新來bash和我被困在試圖否定以下命令:取反,如果在bash腳本

wget -q --tries=10 --timeout=20 --spider http://google.com 
if [[ $? -eq 0 ]]; then 
     echo "Sorry you are Offline" 
     exit 1 

如果,如果我連接到互聯網條件返回true此。我希望它發生其他方式,但把!任何地方似乎不工作。

+1

你把它放在哪裏? '如果! [[...'作品 – 2014-10-20 21:38:52

+1

你也可以這樣使用它:wget your_xxxx_params || (echo「oh oh」&& exit 1) – 2014-10-20 21:49:52

+2

>調用一個subshel​​l只是爲了輸出一個錯誤 – tijagi 2014-10-20 22:03:53

回答

91

您可以選擇:

if [[ $? -ne 0 ]]; then  # -ne: not equal 

if ! [[ $? -eq 0 ]]; then  # -eq: equal 

if [[ ! $? -eq 0 ]]; then 

!分別反轉以下表達式返回。

+6

是否需要雙括號?這是爲什麼? – 2016-12-05 07:25:48

+0

@AlexanderMills:有幾種方法可以做到這一點。使用雙括號或單個括號或使用'test'命令:'if test $? -ne 0;那麼' – Cyrus 2016-12-05 18:05:14

+0

這個答案並不是獨立的。 Eiter解釋了什麼!是並且提供或鏈接到文檔。 – ManuelSchneid3r 2017-05-08 12:14:32

4

您可以使用不等比較-ne而不是-eq

wget -q --tries=10 --timeout=20 --spider http://google.com 
if [[ $? -ne 0 ]]; then 
     echo "Sorry you are Offline" 
     exit 1 
5

如果你感覺懶惰,這裏的處理條件下使用||(或)和&&(和)手術後一個簡潔的方法:

wget -q --tries=10 --timeout=20 --spider http://google.com || \ 
{ echo "Sorry you are Offline" && exit 1; } 
+4

在真實腳本中,您應該將echo命令之後的'&&'改爲';'。原因是如果輸出被重定向到一個完整磁盤上的文件,'echo'將返回失敗,'exit'永遠不會觸發。這可能不是你想要的行爲。 – 2016-01-17 21:06:41

+0

或者你可以使用'set -e',失敗'echo'將會退出腳本 – 2017-09-13 13:21:40

44

更好

if ! wget -q --spider --tries=10 --timeout=20 google.com 
then 
    echo 'Sorry you are Offline' 
    exit 1 
fi 
4

既然你比較數字,您可以使用arithmetic expression,允許的參數和比較簡單的處理:

wget -q --tries=10 --timeout=20 --spider http://google.com 
if (($? != 0)); then 
    echo "Sorry you are Offline" 
    exit 1 
fi 

注意如何代替-ne,你可以只使用!=。在算術方面,我們甚至沒有預先考慮到$參數,即

var_a=1 
var_b=2 
((var_a < var_b)) && echo "a is smaller" 

工作完全正常。不過,這並不適用於$?特殊參數。

此外,由於((...))計算結果爲真,即非零值,具有0非零值的返回狀態爲1,否則返回狀態,我們可以縮短

if (($?)); then 

但這可能會混淆更多的人,而不是節省的擊鍵。

((...))構造在Bash中可用,但不是POSIX shell specification(儘管提及爲可能的擴展)所要求的構造。

這麼說,最好在我看來完全避免$?,如Cole's answerSteven's answer

+0

你確定'((...))'? [** POSIX程序員參考 - 複合命令**](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_04) – 2016-06-04 21:44:40

+0

@ DavidC.Rankin哦,我沒發現!所以它被稱爲擴展,但不是必需的。我會修改。 – 2016-06-04 21:46:48

+1

是的,那個人也總是帶我走。它確實可以通過':)'在shell中簡化生活 – 2016-06-04 21:51:12