使用环境变量转到exec.Command() [英] exec.Command() in Go with environment variable

查看:472
本文介绍了使用环境变量转到exec.Command()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go中运行以下代码:

I would like to run following code in Go:

out, err := exec.Command("echo", "$PATH").Output()

结果是:

$PATH

代替"PATH =/bin ..."的期望值.

Instead of the expected value of "PATH=/bin...".

为什么?怎样获得期望值?

Why? And how can I get the expected value?

推荐答案

您的命令没有被shell解释,这就是为什么预期的变量替换没有发生的原因.

Your command is not being interpreted by a shell, which is why the expected variable substitution is not occurring.

exec软件包文档:

From the exec package documentation:

... os/exec软件包有意不调用系统外壳 并且不会扩展任何全局模式或处理其他扩展, 管道,或通常由Shell完成的重定向.

...the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells.

...

要扩展环境变量,请使用软件包os的ExpandEnv.

To expand environment variables, use package os's ExpandEnv.

因此,在您的示例中要获得预期的结果:

So to achieve the desired result in your example:

out, err := exec.Command("echo", os.ExpandEnv("$PATH")).Output()

值得回顾一下用于获取环境变量并使用最适合您的特定用例的函数集:

It's worth reviewing the set of functions for getting environment variables and using what works best for your particular use case:

  • func ExpandEnv(s string) string -ExpandEnv根据以下内容替换字符串中的$ {var}或$ var当前环境变量的值.未定义变量的引用将替换为空字符串.
  • func Getenv(key string) string -Getenv检索由键命名的环境变量的值.它返回该值,如果不存在该变量,则该值为空.要区分空值和未设置值,请使用LookupEnv.
  • func LookupEnv(key string) (string, bool) -LookupEnv检索由键命名的环境变量的值.如果环境中存在变量,则返回值(可能为空),并且布尔值为true.否则,返回值将为空,布尔值将为false.

这篇关于使用环境变量转到exec.Command()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆