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:

  1. the above syntax not work in csh (or derivatives), nor work in fish. in these non-posix shells, env required local environment modifications.

  2. the -i argument env 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, starting path.)

  3. env resolves name of command executable using path environment variable, possibly modified in env command line. in context pathname resolution not performed (shebang lines, example), using env (with correct full filepath) saves having know precise paths other possible executables. (it reason encountered in shebang lines).

  4. 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 ...) )

  5. 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 of env 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

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -