[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [shell-script] O IF NÃO FUNCIONA PQ ?
From: |
Gustavo Chaves |
Subject: |
Re: [shell-script] O IF NÃO FUNCIONA PQ ? |
Date: |
03 Mar 2005 12:25:00 -0300 |
User-agent: |
Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 |
>>>>> On Thu, 3 Mar 2005 11:17:17 -0300, "Rodolfo Villanova" <address@hidden>
>>>>> said:
> Deve ter ocorrido um erro de digitação na linha do if; como já apontando por
> outros na lista, a sintaxe correta para teste é abrir e fechar colchetes:
> [ ... ]. Troque o "fecha-chaves" ( } ) pelo "fecha-colchete" ( ] ).
Na verdade, não se trata realmente de sintaxe. Mas esse problema é
tão comum que vale a pena tentar melhor.
O 'if' da Bourne Shell (e, por extensão, o da bash e da ksh, entre
outras) não testa expressões diretamente, mas sim o resultado de uma
lista de comandos. A sintaxe é a seguinte (tirado do comando 'help
if' na bash):
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [
else COMMANDS; ] fi
The if COMMANDS are executed. If the exit status is zero, then the
then
COMMANDS are executed. Otherwise, each of the elif COMMANDS are
executed
in turn, and if the exit status is zero, the corresponding then
COMMANDS
are executed and the if command completes. Otherwise, the else
COMMANDS
are executed, if present. The exit status is the exit status of
the last
command executed, or zero if no condition tested true.
Portanto, podemos fazer coisas interessantes do seguinte tipo:
if grep -q meunome *.txt
then echo achei
else echo não achei
fi
Note que o if testa o resultado do comando grep.
O tal colchete ([) que vemos normalmente depois de um if não é um
elemento sintático, mas simplesmente um alias do comando 'test'.
Veja:
$ type -a [
[ is a shell builtin
[ is /usr/bin/[
Ooops. A bash implementa o '[' como uma builtin pra otimizar, mas
note que além da builtin existe um arquivo executável no meu path com
o nome '/usr/bin/['. Vejamos:
$ ls -l /usr/bin/[
-rwxr-xr-x 1 root root 23928 2004-07-16 08:37 /usr/bin/[
Em algums outros UNIXes (eu estou num Linux) o /usr/bin/[ é um link
simbólico para o comando /usr/bin/test.
Experimente um 'man [' pra ver mais sobre isso.
E lembre-se que o if testa comandos, o que abre todo um leque de
possibilidades interessantes.
Gustavo.