2

I can set environment variables like this.

➤ foo=bar env | grep foo
foo=bar

But, what if, I can only get foo=bar string after I execute a command (which is my use-case). The simplest way to emulate this is using a simple echo command.

➤ `echo foo=bar` env | grep foo
zsh: command not found: foo=bar

In this, zsh/bash starts interpreting it as a command. How do I fix this?

shadyabhi
  • 16,675
  • 26
  • 80
  • 131
  • 1
    It's not clear what you are asking. –  Nov 22 '18 at 13:24
  • 1
    FWIW, I find this question very clear. I think it's a good example of [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) (MCVE). – pjh Nov 22 '18 at 19:18

3 Answers3

3

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
pjh
  • 6,388
  • 2
  • 16
  • 17
0

It is working for me as expected. Have you tried like below?

env `echo foo=bar` | grep foo
mohit
  • 2,325
  • 23
  • 48
0

I'm not sure if I understood your question, but try this:

$ echo "hello" && foo=bar env | grep foo
hello
foo=bar
downtheroad
  • 409
  • 4
  • 11