help-bash
[Top][All Lists]
Advanced

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

Re: unexpected behavior


From: Emanuele Torre
Subject: Re: unexpected behavior
Date: Thu, 12 Jan 2023 19:04:35 +0100
User-agent: Mutt/2.2.9 (2022-11-12)

On Thu, Jan 12, 2023 at 06:24:11PM +0100, Christof Warlich wrote:
> can anyone explain why the following line prints 0 instead of 1?:
> 
> $ stat=0; false || echo hi && echo ho && stat=1 | tee /dev/null; echo $stat

You can simplify that example to just

    bash-5.1$ stat=hi; stat=hello | true; echo "$stat"
    hi
    bash-5.1$ stat=hi; stat=hello; echo "$stat"
    hello

Every component of a pipeline is ran in a subshell (escluding the last
part if `shopt -s lastpipe` is used and job control is not active).

Variables assigned in a subshell, assignments made in a subshell (that
is a different process) are not reflected in the main shell
in other execution environment. (`(CODE)` can be used to run `CODE` in a
subshell)

    bash-5.1$ stat=hi; echo "$stat"; (stat=hello; echo "$stat"); echo "$stat"
    hi
    hello
    hi
    bash-5.1$ stat=hi; echo "$stat"; stat=hello; echo "$stat"; echo "$stat"
    hi
    hello
    hello

See <https://mywiki.wooledge.org/BashFAQ/024> and
<https://mywiki.wooledge.org/SubShell>.

> $ stat=0; false || echo hi && echo ho && stat=1 | tee /dev/null; echo $stat

By the way, your code looks weird. What were you trying to do with it?

`tee /dev/null' I guess acts as something equivalent to `cat', but you
are not actually writing anything to it; if you replace it with `true',
you will notice that "hi" and "ho" get printed anyway.

Were you thinking that `echo hi' and `echo ho' are part of the pipeline?

That is not how that command list is parsed. `||' and `&&' have the same
precedence, and have lower precedence than `|'.

That list (with parts groupped by `{ CODE;}`) is equivalent to:

    {
      stat=0
      false || {
        echo hi && {
          echo ho && {
            stat=1 | {
              tee /dev/null
            }
          }
        }
      }
      echo $stat
    }

 emanuele6



reply via email to

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