views:

183

answers:

2

Hi all, sorry if this is a repeated question but

I was trying to figure out env, ( i.e. calling a util with a new environment).

Just as an example my environment variable KDEDIRS = /usr in my current environment and lets say I type:

env -i KDEDIRS=/home/newkdedir env

This outputs KDEDIRS=/home/newkdedir as expected. (i.e calling second env with the new environment)

Now i wanna call say utility echo same way

env -i KDEDIRS=/home/new_kdedir echo ${KDEDIRS}

This is obviously not gonna work bec. shell expands KDEDIRS before it gets to echo. So the output is /usr (i.e. value in the current environment)

Then i try indirection and type in

env -i KDEDIRS=/home/newkdedir echo ${!KDEDIRS} 

This outputs nothing.

I might be a little bit confused about this but how can i make the shell expand that KDEDIRS variable according to the newly created environment for echo?

Thank ya all!

A: 

Usually, you use `env' to give an environment to a command that it spawned off (eg. like you did with in your first snippet). Printing the variable back (that too using a shell builtin) might be possible through some perverse escaping and subshell tricks but it's not a very common use case (atleast not in my experience).

Noufal Ibrahim
+5  A: 

Expansion happens as part of constructing the env command line which also sets the variable. No expansion is done within the execution of that command. So you must add another command line expander as part of that command. E.g.

env -i KDEDIRS=/home/newkdedir /bin/sh -c 'echo $KDEDIRS'
KDEDIRS=/home/newkdedir eval 'echo $KDEDIRS'

Indirection has nothing to do with it.

reinierpost
+1 for a neat example. I gave up with after messing around with escapes for a while.
Noufal Ibrahim
Thanks, sh -c works as another expander as you explained but the line with eval does not work for me. Is it due to Jonathan's comment above?
beegee
The `eval` version gives me: `env: eval: No such file or directory`.
Dennis Williamson
@Dennis: `eval` is a shell builtin. `env` only executes unix executables. The example is wrong.
Charles Stewart
@reinierpost : Can you edit the answer and take out the eval part pls? I don't know if I can edit your answer
beegee
@all: Thanks for the warnings - indeed, the second example doesn't work with env -i prepended, which I had added by mistake. Taken out now.
reinierpost