【问题标题】:Golang exec.Command() bash command not working [duplicate]Golang exec.Command() bash命令不起作用[重复]
【发布时间】:2018-09-11 17:04:47
【问题描述】:

我想使用 golang 的 exec.Command() 运行以下 bash 命令

ls > sample.txt

为此我写了

_,err:=exec.Command("ls",">","sample.txt").Output()

但这似乎不起作用。我知道我可以使用

写入文件
exec.Command().StdoutPipe()

但我想以这种方式单独写作。知道如何在 golang 中做到这一点吗?

【问题讨论】:

  • 如果是bash命令,需要bash来执行。 ls 不能使用 > 作为参数。
  • 反正我可以在 go 中使用频道吗?
  • 我不确定通道与执行命令有什么关系。您要么需要执行一个 shell,要么自己编写输出。

标签: bash go


【解决方案1】:

来自文档:

与来自 C 和其他语言的“系统”库调用不同,os/exec 包有意不调用系统 shell,也不扩展任何 glob 模式或处理通常由 shell 完成的其他扩展、管道或重定向。该包的行为更像 C 的“exec”系列函数。要扩展 glob 模式,可以直接调用 shell,注意转义任何危险的输入,或者使用 path/filepath 包的 Glob 函数。要扩展环境变量,请使用包 os 的 ExpandEnv。

有了这个,我对你正在尝试做的最好的猜测是运行 bash 并将你的命令作为参数传递给它:

out, err := exec.Command("bash", "-c", cmd)

【讨论】: