英文:
golang exec.Command returns exit status 1 with bash
问题
我正在尝试使用bash -c
在exec.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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论