Shell variable expansion - indirection while calli

2019-07-13 19:01发布

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?

2条回答
我命由我不由天
2楼-- · 2019-07-13 19:49

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.

查看更多
Deceive 欺骗
3楼-- · 2019-07-13 19:50

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

查看更多
登录 后发表回答