27

Possible Duplicate:
using single or double bracket - bash

When should I use a single bracket? [

When should I use double brackets? [[

Are both POSIX compliant?

ilkkachu
  • 138,973
Jhonathan
  • 3,605
  • 2
    http://serverfault.com/questions/52034/what-is-the-difference-between-double-and-single-square-brackets-in-bash – perilbrain Sep 24 '12 at 15:27

2 Answers2

18

Single bracket is the traditional form, and is often implemented as an external command. Double bracket is a bash (and ksh and zsh) extension, is not in POSIX, and has the advantage of cleaner syntax (see below) and not using a separate process.

One of the syntax differences is that < and > operators (note: not standard POSIX) don't need to be escaped or quoted to avoid reading as a redirect operator. Also, [ requires some tricks in case one of the strings might be empty or begin with a hyphen. This is why you see scripts do something like [ "x$ASD" == xValue ] whereas with bash they could simply use [[ $ASD == Value ]]. Note that the "x" trick is not strictly necessary with a POSIX-compliant command testing only one thing, see this question for more details about it.

The bash FAQ has for more information about the differences. This has also been answered on another stack exchange site.

Random832
  • 10,666
  • 4
    [ doesn't have < or > operators. If it does it's a nonportable shell extension. The x$var workaround is also unnecessary with POSIX [ - it might have been needed for ancient implementations that had weird parsing quirks, but POSIX [ is very well defined for up to 4 arguments. – jw013 Sep 24 '12 at 15:51
6

Only [ (test) is in POSIX. You won't find [[ specified in POSIX except as a reserved word that implementations may use. Bash does indeed use [[ as an enhanced test operator, and if you are writing scripts targeted specifically for bash, always use [[ because it is much more powerful than [ and safer to use as well. If, however, you are targeting POSIX sh, you need to use [, and make sure to quote arguments and not use more than 4 arguments to [.

jw013
  • 51,212