The problem is that the shell looks for the form var1=val1 var2=val2 ... command
before doing expansions, including command substitution (`...`
or $(...)
).
One way to work around the problem is to use eval
to cause the shell to do its parsing after the command substitution is done:
eval "$(echo foo=bar)" env | grep foo
(See What is the benefit of using $() instead of backticks in shell scripts? for an explanation of why I've changed `...`
to $(...)
.)
Unfortunately, eval
is potentially dangerous. It should not be used unless there is no other alternative. See Why should eval be avoided in Bash, and what should I use instead?.
Another alternative is to use export
in a subshell. One way is:
{ export "$(echo foo=bar)" ; env ; } | grep foo
Since the export
is done in a pipeline (and not the last part of a pipeline, which would make a difference for some shells or some modes) it doesn't affect the variable settings in the current shell. If the command is not in a pipeline, then it would be necessary to explicitly run it in a subshell to get the same effect. E.g.
( export "$(echo foo=bar)" ; env ) > tmpfile
grep foo tmpfile