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?
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.
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).
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.
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.
[[ 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
[[ ]]
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With