Sospecho que esto es intencional (en lugar de simplemente un error). Si es así, diríjame a la documentación pertinente para obtener una justificación.
~$ i=0; ((i++)) && echo true || echo false
false
~$ i=1; ((i++)) && echo true || echo false
true
La única diferencia entre las dos líneas es i=0
vs.i=1
Respuesta1
Esto se debe a i++
que
post-incremento, como se describe en man bash
. Esto significa que el valor de la expresión es eloriginalvalor de i
, no el valor incrementado.
ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and
declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no
check for overflow, though division by 0 is trapped and flagged as an error. The operators and their prece-
dence, associativity, and values are the same as in the C language. The following list of operators is
grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.
id++ id--
variable post-increment and post-decrement
De modo que:
i=0; ((i++)) && echo true || echo false
actúa como:
i=0; ((0)) && echo true || echo false
excepto que i
también se incrementa; y eso:
i=1; ((i++)) && echo true || echo false
actúa como:
i=1; ((1)) && echo true || echo false
excepto que i
también se incrementa.
El valor de retorno de la (( ))
construcción es verdadero ( 0
) si el valor es distinto de cero y viceversa.
También puedes probar cómo funciona el operador post-incremento:
$ i=0
$ echo $((i++))
0
$ echo $i
1
Y pre-incremento para comparar:
$ i=0
$ echo $((++i))
1
$ echo $i
1
Respuesta2
]# i=0; ((i++)) && echo true || echo false
false
]# i=0; ((++i)) && echo true || echo false
true
El valor de 'retorno' de an ((expression))
depende del prefijo o postfijo. Y entonces la lógica es esta:
((expression))
The expression is evaluated according to the rules described be low under ARITHMETIC EVALUATION.
If the value of the expression is non-zero,
the return status is 0;
otherwise the return status is 1.
Esto significa que se convierte en normal, no como un valor de retorno.