在golang中,使用`exec.Command`执行多个bash命令时可能会遇到问题。

huangapple go评论102阅读模式
英文:

exec.Command not working in golang for multiple bash commands

问题

我需要获取一个文件中的变量,并使用golang来实现。我正在尝试以下代码:

cmd1 := exec.Command("bash", "-c", "source fileName|echo $INFO")
out, err := cmd1.Output()
if err != nil {
    log.Fatalf("cmd.Run() failed with %s\n", err)
}
fmt.Printf("combined out:\n%s\n", string(out))

如果我在macOS终端中执行这个命令,我可以看到我需要的信息。但是如果我在go中执行这个命令,输出中什么也没有。
我对go还不熟悉。非常感谢您对此的帮助。

英文:

I need to source a file and get the variables from the file using golang. I am doing as can be seen below:

cmd1 := exec.Command("bash", "-c", "source fileName|echo $INFO")
out, err := cmd1.Output()
if err != nil {
	log.Fatalf("cmd.Run() failed with %s\n", err)
}
fmt.Printf("combined out:\n%s\n", string(out))

If I execute this command in terminal on macos i see the information i need. But if I execute this command within go, I get nothing in the output.
I am new to go. Any help with this is highly appreciated.

答案1

得分: 1

代替使用管道命令,我需要执行以下操作:

cmd1 := exec.Command("bash", "-c", "source fileName; echo $INFO")
英文:

Instead of piping the command, I needed to do the below:

cmd1 := exec.Command("bash", "-c", "source fileName; echo $INFO")

huangapple
  • 本文由 发表于 2022年10月15日 04:08:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/74074380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定