bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Logical expression works does not work as expected


From: Greg Wooledge
Subject: Re: Logical expression works does not work as expected
Date: Fri, 27 Dec 2024 18:47:00 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Sat, Dec 28, 2024 at 00:52:59 +0300, Павел Fortovey wrote:
>    I apologize. I found out that this behavior is not a bug.
> 
>    I didn't think that bash is such a strange scripting language with its
>    own interpretation of the concept of logic.

>    Repeat-By:
> 
>            bash -c "true && true || false && echo bug"

An explanation is useful for the archives.  In a command that chains
both the && and || operators, execution proceeds from left to right,
skipping or executing each internal command based on the value of $?
at that point, and the operator which precedes the command.

Taking the example:

    true && true || false && echo bug

The first command, "true", is always executed.  It sets $? to 0.

The operator after this command is && so we look at $? and execute
the next command only if $? is 0.  Since the previous command did
set $? to 0, the second "true" is also executed.  It sets $? to 0.

The next operator is || so we look at $? and only execute the next
command if $? is nonzero.  Since $? is 0 at this point, we skip the
"false" command and proceed to the next operator.

The next operator is && so we look at $? and only execute the next
command if $? is zero.  $? is 0 at this point (having been set that
way by the second "true" command), so we do in fact execute the
final command.

    hobbit:~$ true && true || false && echo bug
    bug

The final value of $? is whatever it was set to by the last command
executed.  In my case, the echo successfully writes "bug" to stdout,
so $? is set to 0.

You might have been raised on some other language where the && and ||
operators have different precedence.  In the shell language, they have
the same precedence.

In other words, it works like:

    ((true && true) || false) && echo bug

and not like:

    (true && true) || (false && echo bug)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]