Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of double square brackets in bash [duplicate]

Tags:

bash

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?

like image 329
H2ONaCl Avatar asked Jan 24 '13 08:01

H2ONaCl


People also ask

What do double square brackets mean in bash?

Double Brackets i.e. [[]] is an enhanced (or extension) version of standard POSIX version, this is supported by bash and other shells(zsh,ksh). In bash, for numeric comparison we use eq , ne , lt and gt , with double brackets for comparison we can use == , != , <, and > literally. [ is a synonym for test command.

What does || in bash mean?

Just like && , || is a bash control operator: && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero). || means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).

What does square brackets mean in bash?

The square brackets are a synonym for the test command. An if statement checks the exit status of a command in order to decide which branch to take. grep -q "$text" is a command, but "$name" = 'Bob' is not--it's just an expression.

What do double parentheses mean in bash?

construct permits arithmetic expansion and evaluation. In its simplest form, a=$(( 5 + 3 )) would set a to 5 + 3, or 8. However, this double-parentheses construct is also a mechanism for allowing C-style manipulation of variables in Bash, for example, (( var++ )). Example 8-5.


2 Answers

[[ 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

like image 85
vpillai Avatar answered Sep 28 '22 08:09

vpillai


[[ ]] 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

like image 31
DonCallisto Avatar answered Sep 28 '22 08:09

DonCallisto