When I am trying echo variable inside 'env' command I got nothing, but I can see it using 'printenv' command:
root@devel:~# env xxx=23 echo $xxx
root@devel:~# env xxx=23 printenv | grep xxx
xxx=23
what's wrong here?
When I am trying echo variable inside 'env' command I got nothing, but I can see it using 'printenv' command:
root@devel:~# env xxx=23 echo $xxx
root@devel:~# env xxx=23 printenv | grep xxx
xxx=23
what's wrong here?
When you run
env xxx=23 echo $xxx
, the variablexxx=23
becomes visible to theecho
process during its execution. But inecho $xxx
the value of$xxx
is not evaluated byecho
, it is evaluated by the currently executing shell. And since theenv ...
invocation doesn't affect the current shell, the value of$xxx
is whatever it was before you executed this command (probably unset).echo
is not a good way to test the effect ofenv
, because you cannot make theecho
command print a specific value defined in its environment. Your example withprintenv
is better, because it dumps the content of environment variables it knows about. Another good test is what @john wrote in his answer, invoking another shell and make the shell print a chosen environment variable. Any program with the ability to print the content of environment variables would work.In the above, the shell evaluates
$xxx
beforeenv
is executed. Thus, nothing is echoed.In more detail, the shell sees the four words
env
,xxx=23
,echo
and$xxx
. It interpretsenv
as a command name andxxx=23
,echo
, and$xxx
as three arguments which will be passed to the commandenv
. It evaluates$xxx
before passing it to the commandenv
.By contrast, in the following, there are no shell variables for the shell to evaluate. Instead
env
is executed with two arguments,xxx=23
andprintenv
.env
sets the environment variablexxx
and then executesprintenv
:Similarly, observe:
Since
$xxx
is inside single-quotes, the shell does not evaluate it. Instead is runsenv
with four arguments:xxx=23
,sh
,-c
, andecho $xxx
. Afterenv
sets environment variablexxx
, it executessh
with arguments-c
andecho $xxx
. The$xxx
is evaluated whensh
is executed and hence it sees the variablexxx
.