简体   繁体   English

无法使用命令的输出分配env变量

[英]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). 但是,如果我执行命令(这是我的用例)后,我只能得到foo=bar字符串。 The simplest way to emulate this is using a simple echo command. 最简单的模拟方法是使用简单的echo命令。

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

In this, zsh/bash starts interpreting it as a command. 在这里,zsh / bash开始将其解释为命令。 How do I fix this? 我该如何解决?

The problem is that the shell looks for the form var1=val1 var2=val2 ... command before doing expansions, including command substitution ( `...` or $(...) ). 问题是shell在进行扩展之前会查找var1=val1 var2=val2 ... command的形式,包括命令替换( `...`$(...) )。

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使shell在命令替换完成后进行解析:

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 $(...) .) (请参阅在shell脚本中使用$()而不是反引号的好处是什么?解释为什么我将`...`更改为$(...) 。)

Unfortunately, eval is potentially dangerous. 不幸的是, eval具有潜在的危险性。 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? 请参阅为什么要在Bash中避免eval,我应该使用什么呢? .

Another alternative is to use export in a subshell. 另一种方法是在子shell中使用export 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. 由于export是在管道中完成的(而不是管道的最后部分,这会对某些shell或某些模式产生影响),因此它不会影响当前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. 如果命令不在管道中,那么有必要在子shell中显式运行它以获得相同的效果。 Eg 例如

( export "$(echo foo=bar)" ; env ) > tmpfile
grep foo tmpfile

It is working for me as expected. 它按预期为我工作。 Have you tried like below? 你有没有试过下面的?

env `echo foo=bar` | grep foo

I'm not sure if I understood your question, but try this: 我不确定我是否理解你的问题,但试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM