使用[和[[]的条件表达式之间的差异

时间:2012-06-29 04:24:02

标签: bash syntax conditional

之间的确切区别是什么:

if [ $? -ne 0 ];

if [[ $? -ne 0 ]];

2 个答案:

答案 0 :(得分:3)

如上所述here

  

[相反,[[会阻止变量值的分词。因此,如果   VAR="var with spaces",您无需在测试中双引$VAR    - 尽管使用引号仍然是一个好习惯。此外,[[会阻止路径名扩展,因此带有通配符的文字字符串不会尝试   扩展到文件名。使用[[==!=将字符串解释为   正确的shell glob模式要匹配的值   例如:[[ "value" == val* ]]

答案 1 :(得分: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.