[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: The difference between `X=x f | cat` and `{ X=x; f; } | cat`
From: |
Kerin Millar |
Subject: |
Re: The difference between `X=x f | cat` and `{ X=x; f; } | cat` |
Date: |
Thu, 19 Jan 2023 14:36:58 +0000 |
On Thu, 19 Jan 2023 14:30:50 +0000
Kerin Millar <kfm@plushkava.net> wrote:
> On Thu, 19 Jan 2023 08:02:07 -0600
> Peng Yu <pengyu.ut@gmail.com> wrote:
>
> > Hi,
> >
> > f is a function that uses a variable called X, which is not declared in f.
> >
> > As far as I can tell, the following two ways produce the same results.
> >
> > - `X=x f | cat`
> > - `{ X=x; f; } | cat`
>
> They are not equivalent.
>
> $ bash -c 'f() { declare -p X; }; X=x f; declare -p X'
> declare -x X="x"
> bash: line 1: declare: X: not found
>
> $ bash -c 'f() { declare -p X; }; X=x; f; declare -p X'
> declare -- X="x"
> declare -- X="x"
>
> The first version defines X in such a way that it affects only the operating
> environment in which f is run. Note, also, that the variable is marked as
> being exportable, meaning that it would be present in the environment of any
> subprocesses that might be launched by f. For a more rigorous explanation,
> refer to the SIMPLE COMMAND EXPANSION section of the manual.
Here, I forgot to say that, in the case that f is an executable, X will also be
present in the environment of that particular subprocess. Whether it is present
in the environment of any subprocesses in turn would depend on whether f
decides to propagate the environment as it was originally inherited.
--
Kerin Millar