Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: unintuitive bracketing with return value



On Tue, Oct 18, 2022 at 4:47 PM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
>
> [...] shouldn't the brackets do the intuitive thing and
> force the final '||' to be the alternative to the first '&&'?

You seem to be thinking of `X && Y || Z` as a single construct but
there is no such thing. There is only `X && Y` and `X || Y`. In any
programming language I'm familiar with, these operators are
left-associative, short-circuit, and the result is always that of the
last evaluated operand. Short-circuiting means that the second operand
is evaluated by &&/|| if and only if the first operand is true/false.
There are two aspects on which programming languages differ when it
comes to these operators.

1. Is the result coerced to bool (0 or 1)? Yes in C (and other
statically-typed languages), no in Zsh (and other dynamically-typed
languages).
2. Does && have higher precedence than ||? Yes in C (and most
languages), no in Zsh (and all shells).

Once you know this, it should be clear why your program evaluates the
way it does.

So, how do you put this in practice? Use `if` when you need `if`. Use
`X && Y || Z` only when `if` would be wrong. However, even then it's
almost always better to do this:

  if ! X || ! Y; then
    Z
  fi

Roman.




Messages sorted by: Reverse Date, Date, Thread, Author