"[ ]" vs. "[[ ]]" in Bash shell
test
's string equality operator doesn't do globs.
$ [ abc = *bc ] ; echo $?
1
$ [[ abc = *bc ]] ; echo $?
0
[[
is a bash built-in, and cannot be used in a #!/bin/sh
script. You'll want to read the Conditional Commands section of the bash manual to learn the capabilities of [[
. The major benefits that spring to mind:
==
and!=
perform pattern matching, so the right-hand side can be a glob pattern=~
performs regular expression matching. Captured groups are stored in theBASH_REMATCH
array.- boolean operators
&&
and||
- parenthèses for grouping of expressions.
- no word splitting, so it's not strictly necessary to quote your variables.
The major drawback: your script is now bash-specific.
Also - under what circumstances should [ ] be used vs. [[ ]] and vice versa?
It depends. If you care about portability and want your shell scripts to run on a variety of shells, then you should never use [[
. If you want the features provided by [[
on some shells, you should use [[
when you want those features. Personally, I never use [[
because portability is important to me.