[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Clarification on Setting Environment Variables for Command Execution
From: |
Bernhard Voelker |
Subject: |
Re: Clarification on Setting Environment Variables for Command Execution with or without env. |
Date: |
Wed, 5 Jun 2024 09:00:02 +0200 |
User-agent: |
Mozilla Thunderbird |
On 6/4/24 11:45, Hongyi Zhao wrote:
Are there any functional differences between these two methods in
terms of how the environment variables are set and utilized by
my_command?
No, the started process my_command will see the environment variables
regardless whether they are set by the env program or by the shell.
And that's exactly the difference: which program is starting my_command?
$ type export
export is a shell builtin
The 'export' is shell syntax, and the shell is setting up the environment
variable for all the programs started from it.
Like Rob wrote, starting a new process is done via the execve() system call.
shell (setting up environment) --> my_command
In some environments like for a native program, starting another program is
and can only be done via execve(), so the program would have to set up the
environment variables itself ... or it invokes env(1) for doing this for the
final command.
some_program --> env --> my_command
Alternatively, some_program could invoke the shell to setup the environment
variable
and that would launch my_command.
some_program --> shell (export...) --> my_command
e.g.
sh -c "export VAR=value; my_command"
Sometimes we see this pattern for other shell-syntax (pipes, &&, loops,
redirections,
etc.) as well. Here's an example from the find/xargs manual to launch the Emacs
editor for all header files matching a certain pattern:
find /usr/include -name '*.h' \
| xargs grep -l mode_t \
| xargs sh -c 'emacs "$@" < /dev/tty' Emacs
Best practice?
If there's already a shell started, then it's usually easier to use 'export',
otherwise or when starting an intermediate shell many times in a row is too
slow,
then env(1) is often preferred.
Have a nice day,
Berny