Bash se declaração

0

Como todos sabem, a declaração simples if é assim:

if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi

Em seguida, o documento diz:

The TEST-COMMAND list is executed, and if its return status is zero, the CONSEQUENT-COMMANDS list is executed

Significa que o status de retorno do TEST-COMMAND é convertido em booleano verdadeiro / falso usando a regra:

return status - 0 -> true
return status - 1 -> false

e, em seguida, usado pela instrução if para determinar que ação tomar?

    
por Mulligan 24.01.2017 / 19:43

1 resposta

1

Sim. Por exemplo:

$ exitwith() { return $1; }
$ for stat in {0..10}; do
> if exitwith $stat; then
> echo "An exit status of $stat is considered true"
> else
> echo "An exit status of $stat is considered false"
> fi
> done
An exit status of 0 is considered true
An exit status of 1 is considered false
An exit status of 2 is considered false
An exit status of 3 is considered false
An exit status of 4 is considered false
An exit status of 5 is considered false
An exit status of 6 is considered false
An exit status of 7 is considered false
An exit status of 8 is considered false
An exit status of 9 is considered false
An exit status of 10 is considered false

Mas na verdade é um pouco mais complicado do que isso, porque o status de saída é um inteiro não assinado de 8 bits, ele pode variar apenas de 0 a 255; valores fora desse intervalo reduzem o módulo 256 nesse intervalo:

$ for stat in -2 -1 255 256 257; do
> if exitwith $stat; then
> echo "An exit status of $stat (actually $?) is considered true"
> else
> echo "An exit status of $stat (actually $?) is considered false"
> fi
> done
An exit status of -2 (actually 254) is considered false
An exit status of -1 (actually 255) is considered false
An exit status of 255 (actually 255) is considered false
An exit status of 256 (actually 0) is considered true
An exit status of 257 (actually 1) is considered false
    
por 24.01.2017 / 20:17

Tags