3

The following code

if [ $a == "apple" ];
then
    echo "True"
else
    echo "False"
fi

outputs "True" ("False") if a="apple" (a="plum"). The comparison fails if one uses wildcards:

if [ $a == "appl"* ];

and is fixed if one replaces [ by [[:

if [[ $a == "appl"* ]];

What is the difference between [ and [[ in if statements?

Viesturs
  • 943
  • 3
  • 12
  • 16

1 Answers1

2
  • [ is a command (basically a variant of the test command). [[ is a builtin in many shells.
  • When you write foo* inside [...] filename expansion (aka globbing) occurs; while inside [[...]] pattern matching occurs.
  • [[ is more powerful and capable than [ but should not be used if portability is a concern.
  • [ and [[ are not part of the if syntax, you can use them as in [ "$exit" = 'yes' ] && exit.
  • Inside [...] you should prefer = instead of ==. As far as I know, the second one is accepted in many shells but is not POSIX-compliant.

By the way, I recommend you to double-quote your variables even if you really know how word splitting will behave.

nxnev
  • 3,654