On Thu, Apr 18, 2013 at 12:59 PM, and...@coolbox.se <and...@coolbox.se>wrote:
> The ARITHMETIC EVALUATION section of the man page claims equivalence with > C for all the operators, but in reality bash does not perform short circuit > evaluation, which implies that the logical operators do NOT produce the > same results as in C. > Try these, for example: > > f () { > # echo "$@" >&2 > local n=$1 > echo $((0 < n ? n * $(f $((n-1))) : 1)) > } > > or > > g() { > # echo "$@" >&2 > local a=$1 b=$2 > echo $((0 == b ? a : $(g b $((a%b))))) > } > > Note that && and || are affected the same way, and the side effect is not > due solely to recursion. > > $ echo $((1 || $(echo + >&2 && echo 0))) > > $ echo $((0 && $(echo + >&2 && echo 1))) > > The results are correct, but the side effects are NOT the same as in C. > > This may all be fine and as intended, but in that case the documentation > feels somewhat misleading. > > Best, > > --@; > Expansions are not part of the arithmetic evaluation and are done before. So your $( ) and $(( )) inside the outer $(( )) are done before the arithmetic evaluation starts. For the evaluation bash does short-circuit: $ n=0;echo $(( n?++n:n)) 0 $ n=1;echo $(( n?++n:n)) 2 $ n=0;echo $(( 1 && ++nn));echo $n 1 0