contrapositive
contrapositive

Reputation: 1531

Difference between conditional expressions using [ and [[

What's the precise difference between:

if [ $? -ne 0 ];

and

if [[ $? -ne 0 ]];

Upvotes: 2

Views: 276

Answers (2)

dinox0r
dinox0r

Reputation: 16039

As stated here:

Contrary to [, [[ prevents word splitting of variable values. So, if VAR="var with spaces", you do not need to double quote $VAR in a test - eventhough using quotes remains a good habit. Also, [[ prevents pathname expansion, so literal strings with wildcards do not try to expand to filenames. Using [[, == and != interpret strings to the right as shell glob patterns to be matched against the value to the left, for instance: [[ "value" == val* ]].

Upvotes: 3

Michael Hoffman
Michael Hoffman

Reputation: 34314

There is none. The [[...]] syntax introduces some other things you can do with conditional expressions, though. From 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.

Upvotes: 2

Related Questions