0

Why is this 0?

$ echo $(( 0 && 0 ))
0

Why is this 0?

$ echo $(( 1 && 0 ))
0

Why is this 0?

$ echo $(( 0 && 1 ))
0

Why is this 1?

$ echo $(( 1 && 1 ))
1
1
  • Why "opposite way"?
    – user373503
    Commented May 15, 2020 at 5:54

2 Answers 2

3

This matches the definition of “logical and”, which is what && represents in an arithmetic context. The truth table is as follows:

  |  F  |  T
--+-----+-----
F |  F  |  F
--+-----+-----
T |  F  |  T

“A and B” is true only if both A and B are true.

In the shell’s arithmetic context, operators are implemented as defined in the C standard, where “true” is any non-zero value and “false” is zero. This is indeed the opposite of exit codes, where “true” (or rather, “success”) is zero and “false” (or rather, “error”) is any non-zero value.

See also:

$ echo $((2 && 2))
1

$ echo $((-1 && 2))
1
2
  • Another piece of the "comes out the opposite way" puzzle is that 0 is false in an arithmetic context, while an exit-status of 0 is true in the context of the shell.
    – Kusalananda
    Commented May 15, 2020 at 6:27
  • Ah, thanks, that’s where the confusion comes from! I missed that... Commented May 15, 2020 at 7:27
1

man $SHELL

tells

&&     logical AND

So the rule is right side will be evaluated only if left side is TRUE. Since you are using the convention of 0 and 1. 0 is FALSE and 1 is TRUE.

Now lets discuss the code and then explanation.

echo $(( 0 && 0 ))

&& - will not evaluate the right side as left side is 0 and hence prints 0

$ echo $(( 1 && 0 ))

&& - will evaluate the right side as left side is 1 and sadly the right side is 0 and hence prints 0

echo $(( 0 && 1 ))

&& - will not evaluate the right side as the left side is 0 and hence prints 0

echo $(( 1 && 1 ))

&& - will evaluate the right side as the left side is 1 and hurray the right side is also 1 and hence prints 1.

Edit

As pointed by one user , the SHELL && has a property of short-circuit (along with logical) . And point to be noted is logical not equivalent to short-circuit all the time.

3
  • Note that “logical and” doesn’t necessarily imply short-circuiting; it’s described as “logical” to distinguish it from “binary”. Making it short-circuiting is a separate concern, specified for the shell because its && operator (along with other arithmetic operators) is specified as being equivalent to the corresponding C operator (see the relevant section of POSIX). Commented May 14, 2020 at 13:35
  • @Stephen Kitt ok . I got your point. SHELL && alone short-circuit. But generally logical is not equivalent to short-circuit. Commented May 15, 2020 at 2:28
  • My point is that your answer says that “So the rule is right side will be evaluated only if left side is TRUE”, seemingly presenting that as a consequence of the fact that “&&” is “logical AND”, but it’s not a consequence of that. Commented May 15, 2020 at 8:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .