help-bash
[Top][All Lists]
Advanced

[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: Emanuele Torre
Subject: Re: The difference between `X=x f | cat` and `{ X=x; f; } | cat`
Date: Thu, 19 Jan 2023 15:54:29 +0100
User-agent: K-9 Mail for Android

On 19 January 2023 15:02:07 CET, 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`

> What is their difference under the hood? Is there any timing
> difference between the two calls?

You don't have to look under the hood to see differences. Obviously, in
the first command, X is always exported; while in the second command X
is only exported if it was already exported.

  bash-5.1$ f () { env | grep MYX ;}
  bash-5.1$ unset -v MYX
  bash-5.1$ MYX=x f | cat
  MYX=x
  bash-5.1$ { MYX=x; f ;} | cat
  bash-5.1$ export MYX=y
  bash-5.1$ { MYX=x; f ;} | cat
  MYX=x

Maybe if you had used export, we could consider them somewhat similar;
otherwise they are just not.

About details; I am pretty sure using  { export X=x; f ;} | ...  instead of
X=x f | ...  or  (export X=x; f)  actually prevents bash from
optimising away fork/wait if f is an external command.

 emanuele6


reply via email to

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