Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

shell - How does AND and OR operators work in Bash?

I tried the following command on bash

echo this || echo that && echo other

This gives the output

this
other

I didn't understand that!

My dry run goes this way :

  1. echo this || echo that && echo other implies true || true && true
  2. Since, && has more precedence than ||, the second expression evaluates first
  3. Since, both are true, the || is evaluated which also gives true.
  4. Hence, I conclude the output to be:

that

other

this

Being from a Java background where && has more precedence than ||, I am not able to relate this to bash.

Any inputs would be very helpful!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From man bash

3.2.3 Lists of Commands

A list is a sequence of one or more pipelines separated by one of the operators ‘;’, ‘&’, ‘&&’, or ‘||’, and optionally terminated by one of ‘;’, ‘&’, or a newline.

Of these list operators, ‘&&’ and ‘||’ have equal precedence, followed by ‘;’ and ‘&’, which have equal precedence.

So, your example

echo this || echo that && echo other

could be read like

(this || that) && other

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...