Both [
and [[
" are used to evaluate what is between [..]
or [[..]]
, you can compare strings and check the file types.
[
is a synonym for test
, [[
is a keyword .
By doing if [ condicao ]
you can say equivalent to if test condicao
, because [
is a token that will invoke the command test
.
The right bracket ]
is not strictly required, however in newer versions of Bash is required.
~$ type test
test is a shell builtin
~$ type '['
[ is a shell builtin
~$ type '[['
[[ is a shell keyword
~$ type ']]'
]] is a shell keyword
~$ type ']'
bash: type: ]: not found
[[..]]
is more flexible than [..]
, while using [[..]]
you can avoid some logic errors in script . For example, the &&
, ||
, <
, and >
operators operate on [[..]]
, but not [..]
.
See an example:
if [ -f $foo && -f $bar && -f $baz ] # Erro
if [ -f $foo ] && [ -f $bar ] && [ -f $baz ] # OK. Cada expressão dentro de um [..]
if [ -f $foo -a -f $bar -a -f $baz ] # OK. Tem que usar "-a" na antes da expressão
if [[ -f $foo && -f $bar && -f $baz ]] # OK!
The difference and when and which to use between [
and [[
according to BashFAQ - 031 is:
To cut a long story short: test
implements the old, portable syntax of
the command. In almost all shells (the oldest Bourne shells are the
exception), [
is a synonym for test
(but requires a final argument of
]
).
Although all modern shells have built-in implementations of [
,
there is still an external executable of that name, e.g. /bin/[
.
[[
is a new improved version of it, which is a keyword, not a program.
This has beneficial effects on the ease of use, as shown below.
[[
is understood by KornShell and BASH (eg 2.03 ), but not by the older POSIX or Bourne shell .
[...]
When should the new test command [[
be used, and when the old one [
?
If portability to the BourneShell is a concern, the old syntax should
be used. If on the other hand the script requires BASH or KornShell ,
the new syntax is much more flexible.
Although
[
and
[[
have a lot in common and share many expression operators like
-f
,
-s
,
-n
,
-z
, there are some notable differences.
Here is a comparison list:
Credits: BashFAQ - 031