Ambos [
e [[
são usados para avaliar o que estiver entre [..]
ou [[..]]
, pode-se comparar strings e verificar os tipos de arquivo.
[
é um sinônimo para test
, [[
é uma palavra-chave.
Ao fazer if [ condicao ]
pode-se dizer equivalente a if test condicao
, pois [
é um token que vai invocar o comando test
.
O colchete direito ]
, não é estritamente necessário, no entanto em versões mais recentes do Bash é exigido.
~$ 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
[[..]]
é mais flexível que [..]
, ao usar [[..]]
pode-se evitar alguns erros de lógica no script. Por exemplo, os operadores &&
, ||
, <
, e >
funcionam no [[..]]
, mas não em [..]
.
Veja um exemplo:
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!
A diferença e quando e qual usar entre [
e [[
segundo o BashFAQ - 031 é:
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 usually still is 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 (e.g. 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.
Embora [
e [[
têm muito em comum e compartilham muitos operadores de expressão como -f
, -s
, -n
, -z
, existem algumas diferenças notáveis.
Aqui está uma lista de comparação:

Créditos: BashFAQ - 031