Skip to main content

ZC5001 - Double Bracket Test

Descrição

Use [[ ]] em vez de [ ] para testes condicionais no zsh.

Exemplo Problemático

#!/bin/zsh

# Sintaxe antiga de colchete simples
if [ "$name" = "John" ]; then
echo "Hello John"
fi

# Problemas com variáveis vazias
if [ $undefined = "value" ]; then # Erro se $undefined está vazio
echo "Match"
fi

Problemas Com [ ] (Colchete Simples)

  1. Word splitting - Variáveis são expandidas e sofrem splitting
  2. Globbing - Caracteres como * são interpretados
  3. Erro com variáveis vazias - [ $var = "value" ] vira [ = "value" ] se $var é vazio
  4. Sintaxe mais restritiva - Precisa de espaços em lugares específicos

Solução Correta

Use colchetes duplos [[ ]] - sintaxe nativa do zsh:

#!/bin/zsh

# Mais seguro e legível
if [[ "$name" == "John" ]]; then
echo "Hello John"
fi

# Funciona mesmo com variáveis vazias
if [[ $undefined = "value" ]]; then # Seguro!
echo "Match"
fi

# Pattern matching integrado
if [[ "$filename" == *.txt ]]; then
echo "É um arquivo de texto"
fi

Correção Automática

O ZshCheck pode converter automaticamente:

zshcheck --fix script.zsh

Antes:

if [ "$x" = "y" ]; then

Depois:

if [[ "$x" = "y" ]]; then

Recursos Exclusivos de [[ ]] no Zsh

Pattern Matching

#!/bin/zsh

# Globbing dentro do teste
if [[ "$file" == *.@(txt|md) ]]; then
echo "Arquivo de texto ou markdown"
fi

# Regex matching
if [[ "$email" =~ ^[a-z]+@[a-z]+\.com$ ]]; then
echo "Email parece válido"
fi

Operadores Lógicos

#!/bin/zsh

# && e || dentro do [[ ]]
if [[ -f "$file" && -r "$file" ]]; then
echo "Arquivo existe e é legível"
fi

# Negação simples
if [[ ! -d "$path" ]]; then
echo "$path não é um diretório"
fi

Comparação de Strings

#!/bin/zsh

# Lexicográfica
if [[ "$a" < "$b" ]]; then
echo "$a vem antes de $b"
fi

# Comprimento
if [[ ${#str} -gt 10 ]]; then
echo "String tem mais de 10 caracteres"
fi

Quando [ ] Ainda é Necessário

Use [ ] apenas quando:

  • Precisa de compatibilidade POSIX (scripts em /bin/sh)
  • Está explicitamente escrevendo para POSIX sh
  • Usando test command diretamente

Para zsh puro, sempre use [[ ]].

Referências