golang的exec.Command在bash中返回退出状态1。

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

golang exec.Command returns exit status 1 with bash

问题

我正在尝试使用bash -cexec.Command中运行多个命令。当我手动运行该命令时,它没有返回错误,命令的输出为nil,但这没关系。我不知道为什么通过golang的exec.Command运行时会返回exit status 1

以下是我的代码:

cmd := exec.Command("bash", "-c", "blkid -o device | grep -v part | grep /dev/mapper")
_ = cmd.Wait()
stdout, err := cmd.Output()

我甚至尝试了这个来自另一个问题的答案,但也没有成功。重要的是,当我在输出不为nil的虚拟机上运行命令时,命令成功执行,但当我在输出为nil的Centos上尝试时失败。

英文:

I am trying to run multiple commands using bash -c in exec.Command, when i manually run the command, it returns no error the output of command is nil but it's okay. I don't know why it returns exit status 1 when i run it through golang exec.Command.

Here is my code :

cmd := exec.Command("bash", "-c", "blkid -o device | grep -v part | grep /dev/mapper")
_ = cmd.Wait()
stdout, err := cmd.Output()

I even tried this answer from another question, but it also didn't worked out.
The important thing is that when i run command on a vm where output is not nil the command executes successfully, but when i tried this on Centos where output is nil it failed.

答案1

得分: 1

这是因为你需要将命令传递给字符串切片。使用以下代码替代:

cmd := exec.Command("bash", []string{"-c", "blkid -o device | grep -v part | grep /dev/mapper"})
stdout, err := cmd.Output()
英文:

This is because you have to pass the command in the string slice.
Use this instead -

cmd := exec.Command("bash",strings.Fields("-c blkid -o device | grep -v part | grep /dev/mapper"))
stdout, err := cmd.Output()

huangapple
  • 本文由 发表于 2021年6月3日 15:37:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/67817294.html
匿名

发表评论

匿名网友

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

确定