Sato Sato - 4 years ago 92
Bash Question

Why this bash shortcuts does not work?

I have a test script like this:

asdf() {
return 1

asdf && echo 123 && exit
echo 321

321 is outputed instead of 123

Why is that?

Answer Source

The && operator is a logical AND. It does lazy evaluation : if the statement to the left evaluates to false (i.e. non-zero return code), then applying the logical AND will still evaluate to false anyway, so evaluating the right part is useless (in the logical predicate sense).

Since your function returns 1 (false as far as Bash is concerned), everything to the right is ignored, your exit is not reached, and the echo statement is executed.

If you want to force execution of all commands on that line, use this instead:

{ asdf ; echo 123 ; exit ; }

A command list like this will always evaluate every one of them, irrespective of their return code. Please note that the last semi-colon is mandatory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download