我正在尝试使用exec.Command()
在Go中执行命令集。我在哪里尝试使用Docker Exec分离Gluster对等端。
fmt.Println("About to execute gluster peer detach")
SystemdockerCommand := exec.Command("sh", "-c", "docker exec ", "9aa1124", " gluster peer detach ", "192.168.1.1", " force")
var out bytes.Buffer
var stderr bytes.Buffer
SystemdockerCommand.Stdout = &out
SystemdockerCommand.Stderr = &stderr
err := SystemdockerCommand.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
}
fmt.Println("System Docker exec : " + out.String())
我期待的结果是“没有同伴要离开”。但是得到了 退出状态1:“ docker exec”至少需要2个参数。
答案 0 :(得分:3)
由于使用了sh -c
,因此下一个参数应该是完整命令或以下命令:
SystemdockerCommand := exec.Command("sh", "-c", "docker exec 9aa1124 gluster peer detach 192.168.1.1 force")
更一般地说,as in here:
cmd := exec.Command("/bin/sh", "-c", "command1 param1; command2 param2; command3; ...")
err := cmd.Run()
请参见this example:
sh := os.Getenv("SHELL") //fetch default shell
//execute the needed command with `-c` flag
cmd := exec.Command(sh, "-c ", `docker exec 9aa1124 ...`)
或者this one,将您的命令放在字符串首位:
cmd := "cat /proc/cpuinfo | egrep '^model name' | uniq | awk '{print substr($0, index($0,$4))}'"
out, err := exec.Command("bash","-c",cmd).Output()
if err != nil {
return fmt.Sprintf("Failed to execute command: %s", cmd)
}
答案 1 :(得分:1)
有什么方法可以在exec.Command中执行多个命令
否。