[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: unexpected behavior
From: |
Davide Brini |
Subject: |
Re: unexpected behavior |
Date: |
Thu, 12 Jan 2023 18:55:07 +0100 |
On Thu, 12 Jan 2023 18:24:11 +0100, Christof Warlich <cwarlich@gmx.de>
wrote:
> Hi,
>
> 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 hi
> ho
> 0
>
> It does what I'd expect when removing the pipe, so it's obviously caused
> by some pipe magic going on ...:
>
> $ stat=0; false || echo hi && echo ho && stat=1; echo $stat
> hi
> ho
> 1
Yes, introducing the pipe makes the "stat=1" part run in a subshell, so the
change is not seen in the parent shell. Here's another simple example:
x=0; x=1 | cat; echo $x # 0
x=0; echo 10 | read x; echo $x # 0
(the previous one would work in some shells; just not in bash with
the default settings)
One possible workaround is to use the value you need while still in the
subshell, for example:
x=0; echo 10 | { read x; echo $x; } # 10
See also https://mywiki.wooledge.org/BashFAQ/024 for more details.
--
D.