Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining || and && in bash [duplicate]

When I execute this in the following line in my shell

echo this || echo that && echo other

The output is:

this
other

Now I don't understand how echo other is executed, because echo that does not return a successful exit status because it is not executed. The && operator only executes the right command when the left command exits successfully.

Does this mean the && operator will execute the righthand command if anything on the left side exits successfully?

like image 625
Xenon Avatar asked Jul 03 '26 07:07

Xenon


2 Answers

Using both || and && in the same line of code, is not a good practice, while it might work on some cases/situations, that does not mean it will work on all cases.

see http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3

Always use an if statement if you feel like doing a short circuit.

Command grouping is a work around if you really need to do that, using the { }

echo this || { echo that && echo other; }
like image 126
Jetchisel Avatar answered Jul 06 '26 04:07

Jetchisel


You can rewrite that example as:

(echo this || echo that) && echo other

You say echo that does not return a successful exit status, but rather, it doesn't return anything at all - it is not executed. So the expression (echo this || echo that) has a successful result (the return of echo this), which makes echo other be executed.

A good example for this situation is just running echo this || echo that - it has a return value of 0, as such, not executing echo that does not turn it into a failure.

like image 44
Leonardo Dagnino Avatar answered Jul 06 '26 05:07

Leonardo Dagnino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!