Poseemos la mejor solución que encontramos por todo internet. Nosotros esperamos que te sea de mucha utilidad y si quieres aportar alguna mejora hazlo con libertad.
Solución:
Las pruebas que había enumerado:
- Paréntesis simple – (…) está creando una subcapa
- Paréntesis doble: ((…)) es para operaciones aritméticas
- Corchete simple – [ … ] es la sintaxis para POSIX
test
- Corchetes Dobles – [[ … ]]es la sintaxis de las expresiones condicionales de bash (similar a
test
pero más poderoso)
no son exhaustivos, puede utilizar lógica booleana
if command; then ...
también, porque los comandos tienen estado de salida. En bash
, 0
es true
y > 0
es false
.
Puede ver el estado de salida de esta manera:
command
echo $?
Ver :
http://wiki.bash-hackers.org/syntax/basicgrammar
http://wiki.bash-hackers.org/syntax/arith_expr
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
El shell en sí solo ejecuta el comando y evalúa su código de salida. Un código de salida cero significa éxito; todos los demás valores indican falla.
if command; then
: things to do if the exit code from command was 0
else
: things to do if it was not 0
fi
while command; do
: things to do if the exit code was 0
done
El comando [
(aka test
) is very commonly used in conditionals, because the original Bourne shell lacked built-in operators to check if a string was empty or a file existed. Modern shells have this command built in, and many shells have an extended and modernized version [[
, but this is not properly portable to POSIX sh
and should thus be avoided for portable scripts. This related question explains the differences between the two in more detail.
The notation (( ... ))
introduces an arithmetic context. Again, this was something which was not part of the original Bourne shell (it had a dedicated external tool expr
for these things) but modern shells have this built in. The result code of an arithmetic expression is 0 if the result of the arithmetic evaluation was not 0 (or an error).
The notation ( command )
creates a subshell and evaluates command
in that. There are situations where this is actually necessary and useful, but if you are only just learning the syntax, you are unlikely to need this.
… In fact, in the majority of scripts I have seen this used in a conditional, it was clearly unnecessary.
Another antipattern to look out for is
command
if [ $? = 0 ]; entonces: cosas fi
Casi nunca debería necesitar examinar $?
explícitamente, y en particular, compararlo con cero es algo if
y while
específicamente hacer por ti detrás de escena. Esto simplemente debe ser refactorizado para
if command; then
: ...
Nos encantaría que puedieras dar visibilidad a esta división si si solucionó tu problema.