shadyabhi
shadyabhi

Reputation: 17234

Unable to assign env variable using a command's output

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?

Upvotes: 2

Views: 193

Answers (3)

pjh
pjh

Reputation: 8209

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

Upvotes: 3

downtheroad
downtheroad

Reputation: 419

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

$ echo "hello" && foo=bar env | grep foo
hello
foo=bar

Upvotes: 0

mohit
mohit

Reputation: 2469

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

env `echo foo=bar` | grep foo

Upvotes: 0

Related Questions