Difference between [[ ]] AND [ ] or (( )) AND ( ) in Bash
((...))
is the shell's arithmetic construct. The operators you can use are documented in the manual: 6.5 Shell Arithmetic
(...)
is a grouping construct that executes the contained commands in a subshell: 3.2.4.3 Grouping Commands
[...]
is the "legacy" conditional construct. Documentation is at 6.4 Bash Conditional Expressions
[[...]]
does everything that [...]
does. The difference is that word splitting and glob expansion are not performed for variables inside [[...]]
so quoting the variables is not so crucial. Additionally, [[
can do pattern matching with the ==
operator and regular expression matching with the =~
operator.
The reason [[ 10 > 9 ]]
gives you an unexpected result is that the >
operator inside [[...]]
is for string comparison and the string "10" is "less than" the string "9".
I would have put this in a comment, but am not yet allowed to.
One difference I have noticed between [] and [[]], is that in the former it is possible to use multiple comparisons.
The same comparison throws a syntax error in [[]]
a=1
b=2
This works:
$ [ "$a" -gt 0 -a "$b" -gt "$a" ] && { echo '[b>a>0]'; }
[b>a>0]
This does not work:
$ [[ $a -gt 0 -a $b -gt $a ]] && { echo '[[b>a>0]]'; }
-bash: syntax error in conditional expression
-bash: syntax error near `-a'
I haven't really dug in to see why that is so, but when using multiple comparisons, I use [].