bash - Is there an advantage to using env for setting variable for a subshell? -
i came across samples set environment variable , launch subprocess in same command:
$ test="test" sh -c 'echo $test"
previously, had used env that:
$ env test="test" sh -c 'echo $test"
can point me @ explanation of first example? there advantage using env this?
there few reasons use env
. of time can (and should) use simpler syntax:
var=value ... command
which posix standard, , should available in posix compatible shell (including /bin/sh
).
here few cases in env
useful:
the above syntax not work in
csh
(or derivatives), nor work infish
. in these non-posix shells,env
required local environment modifications.the
-i
argumentenv
starts indicated command environment containing only specified environment variables. can used run untrusted command without leaking information through environment variables. (but careful: environment variables must set normal functioning, startingpath
.)env
resolves name of command executable usingpath
environment variable, possibly modified inenv
command line. in context pathname resolution not performed (shebang lines, example), usingenv
(with correct full filepath) saves having know precise paths other possible executables. (it reason encountered in shebang lines).the arguments
env
expanded shell before env invoked. consequently, possible compute name of environment variable, not possible using standard shell syntax:env "$name=$value" command ...
this particularly useful when expanding environment array (in bash):
env -i "${new_env[@]}" command ...
(here,
new_env
expected array of form(var1=val1 var2=val2 ...)
)env
without command print (possibly modified) environment out, 1 environment variable per line. don't find feature useful, it's in posix rationale continued existence ofenv
utility:some have suggested env redundant since same effect achieved by:
name=value ... utility [ argument ... ]
the example equivalent env when environment variable being added environment of command, not when environment being set given value. env utility writes out current environment if invoked without arguments. there sufficient functionality beyond example provides justify inclusion of env.
Comments
Post a Comment