help-bash
[Top][All Lists]
Advanced

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

Re: unexpected behavior


From: Greg Wooledge
Subject: Re: unexpected behavior
Date: Thu, 12 Jan 2023 12:48:28 -0500

On Thu, Jan 12, 2023 at 06:24:11PM +0100, Christof Warlich 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

Simplifying it should help make it clear:

unicorn:~$ stat=0; stat=1 | cat; echo "$stat"
0

There are three commands here:

stat=0
stat=1 | cat
echo "$stat"

The first and the third are executed in the current shell.  The second
one is a pipeline, so each command within it is executed in a separate
subshell.

Since stat=1 occurs in a subshell, which has its own private copy of
the variable, the change isn't reflected in the main shell (the script).

Yours has additional complexity that ultimately has no effect on the
question.  In the end, stat=1 is performed in a subshell, because it's
part of a pipeline.



reply via email to

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