2012-06-29 61 views
2

什麼之間的精確區別:區別使用[和[

if [ $? -ne 0 ]; 

if [[ $? -ne 0 ]]; 
+0

'['(通常)是一個程序的名稱。這應該有助於解釋一些差異。 – 2012-06-29 04:31:41

+0

在bash中,'['是內建函數(嘗試'類型['),但'['通常也是一個外部程序。 –

+1

請參閱[BashFAQ/031](http://mywiki.wooledge.org/BashFAQ/031)。 –

回答

3

如前所述here

相反[[[防止變量值的分詞。因此,如果 VAR="var with spaces",您不需要在測試 中雙引號$VAR - 儘管使用引號仍然是一個好習慣。另外,[[可防止路徑名擴展,因此帶通配符的文字字符串不會嘗試將 擴展爲文件名。使用[[==!=將字符串解釋爲 右側,作爲要與左側的值匹配的值,例如:[[ "value" == val* ]]

+1

一個小小的附錄:像預防分詞和路徑名稱擴展這樣的能力是這樣一個事實造成的結果,[[''與[''是一個外部命令相比是內置的]「。 – Samveen

+1

@Samveen:'['是外部命令。但它也是內建的。 –

2

有沒有。儘管如此,[[ ... ]]語法還介紹了可以對條件表達式執行的其他操作。從help [[

Returns a status of 0 or 1 depending on the evaluation of the conditional 
expression EXPRESSION. Expressions are composed of the same primaries used 
by the `test' builtin, and may be combined using the following operators: 

    (EXPRESSION) Returns the value of EXPRESSION 
    ! EXPRESSION    True if EXPRESSION is false; else false 
    EXPR1 && EXPR2 True if both EXPR1 and EXPR2 are true; else false 
    EXPR1 || EXPR2 True if either EXPR1 or EXPR2 is true; else false 

When the `==' and `!=' operators are used, the string to the right of 
the operator is used as a pattern and pattern matching is performed. 
When the `=~' operator is used, the string to the right of the operator 
is matched as a regular expression. 
+0

沒有,但這裏有一些? –

+0

是的,'[$?'的結果完全沒有區別。 -ne 0]'和'[[$?一個0]]。 –

+0

Ahhh ...Touché。 –