13

At this question in the answer from Kyle Brandt the [[ ]] construct is described as a "bash built-in test command". The following is shown as an example.

  if [[ ( $a -gt 2 ) && ( $a -lt 5 ) ]]; then ...

Why are double square brackets, literally [[ ]], necessary?

Community
  • 1
  • 1
H2ONaCl
  • 10,644
  • 14
  • 70
  • 114

2 Answers2

10

[[ is a much more versatile version of [ in bash.

For example, Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example, the &&, ||, <, and > operators work within a [[ ]] test, despite giving an error within a [ ] construct.

also, their implementations are different

-bash-3.2$ type [
[ is a shell builtin
-bash-3.2$ type [[
[[ is a shell keyword

Refer here for a good explanation

vpillai
  • 374
  • 1
  • 3
  • 15
  • 2
    It's worse than that; `[ "$this" > "$that" ]` won't give an error, it'll just do something completely different from what you expected. (Specifically: it'll redirect output to the file specified by `$this`, then test whether `$that` is nonblank.) – Gordon Davisson Jan 24 '13 at 17:21
3

[[ ]] are equal to test keyword.

You can also use [ ] but [[ ]] isn't compatible with all shell types

To me, if I understand the real sense of question, question itself isn't well-formulated.
Those brackets have to be here not so much for order determination, but because the bash synopsis require them

Edit

Question is changed, so my answer too.

[[ ]] is used against [ ] because you don't have to worry about quoting the left hand side of the test that will be read as a variable.
Moreover, < and > doesn't need to be escaped

Community
  • 1
  • 1
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • If I can use `[ ]`, are you saying there is never a reason to use `[[ ]]`. – H2ONaCl Jan 24 '13 at 08:10
  • You're right, the order of operations has nothing to do with the question so I edited the question to remove any mention of `( )` determining the order of operations. – H2ONaCl Jan 24 '13 at 08:11
  • @broiyan: if you haven't to worry about being portable, someone supports that `[[ ]]` is better because you don't have to worry about quoting the left hand side of the test will be read as a variable. Moreover, `<` and `>` doesn't need to be escaped – DonCallisto Jan 24 '13 at 08:13
  • @broiyan: take a look at my update – DonCallisto Jan 24 '13 at 08:20
  • A quick scroll through this link http://wiki.bash-hackers.org/commands/classictest does not seem to turn up any information on why one would double the square brackets. I don't know what you mean by the "left hand side" of the test. – H2ONaCl Jan 24 '13 at 09:11
  • @broiyan: yes, it was a typo. However, try it yourself and you'll discover that what I told you is real :) – DonCallisto Jan 24 '13 at 09:12