i'd argue that env(1)'s name has mislead you --- it's most _commonly_
used just for the "do a $PATH lookup" side-effect, so a shell script
only has assume that it knows where _env_ lives, without having to
assume that it knows where (say) python lives. so `#!/usr/bin/env
python` rather than `#!/usr/bin/python`, for example.

(similarly, it's also a useful portable-between-shells way to say "i
want to call the _real_ command here, not an alias or shell builtin".)

using env to set environment variables is probably most useful when
used in conjunction with env's -i option to _clear_ the environment,
in cases where you don't want to say "this command should _also_ have
FOO=BAR in its environment", but want to say "this command should
_only_ have FOO=BAR in its environment". (though not only do i
anecdotally not see that very often, in the source that's easily
available for me to search, it genuinely doesn't occur very often.)

see also 
https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/env.html,
in particular the RATIONALE section (in particular, the very last
part, about whether env(1) is actually redundant).

On Thu, Jun 6, 2024 at 11:28 AM Hongyi Zhao <hongyi.z...@gmail.com> wrote:
>
> On Wed, Jun 5, 2024 at 5:24 PM Collin Funk <collin.fu...@gmail.com> wrote:
> >
> > Hi,
> >
> > Hongyi Zhao <hongyi.z...@gmail.com> writes:
> >
> > > Using env command:
> > >
> > > env PATH="/custom/path:$PATH" my_command
> > >
> > > Directly setting the environment variable:
> > >
> > > PATH="/custom/path:$PATH" my_command
> > [...]
> > > In what scenarios would it be more appropriate to use env versus
> > > directly setting the environment variable? Are there specific
> > > advantages or disadvantages associated with each method?
> >
> > One minor problem is that csh [1] doesn't use the same syntax for
> > variable assignment. Up until recently FreeBSD used csh as the default
> > login shell for root accounts. I doubt you will run into the problem
> > anywhere else.
> >
> > Here is an example:
> >
> >     $ bash
> >     $ env | grep '^VAR'
> >     $ env VAR='abc' | grep '^VAR'
> >     VAR=abc
> >     $ VAR='abc' env | grep '^VAR'
> >     VAR=abc
> >     $ csh
> >     % env | grep '^VAR'
> >     % env VAR='abc' | grep '^VAR'
> >     VAR=abc
> >     % VAR='abc' env | grep '^VAR'
> >     VAR=abc: Command not found.
> >
> > You could use:
> >
> >     % setenv VAR 'abc' ; env | grep '^VAR'
> >
> > But that would set the environment variable in the parent process which
> > isn't the intention.
> >
> > Collin
> >
> > [1] https://en.wikipedia.org/wiki/C_shell
>
> Thank you very much to everyone here for their responses to this
> issue. I need to carefully read the relevant explanations and further
> observe in subsequent practices to see if I have fully understood the
> issue or if there are still areas that need further discussion.
>
> Regards,
> Zhao
>

Reply via email to