dptsivmg82908
2019-07-02 04:34
浏览 1.2k
已采纳

有什么办法可以在exec.Command中执行多个命令?

I am trying to execute set of commands in Go using exec.Command(). Where I am trying to detach Gluster peer using Docker Exec.

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())

I was expecting a result as "no peer to detatch". But got exit status 1: "docker exec" requires at least 2 arguments.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongqu4443 2019-07-02 04:59
    已采纳

    Since you have used sh -c, the next parameter should be the full command or commands:

    SystemdockerCommand := exec.Command("sh", "-c", "docker exec 9aa1124 gluster peer detach 192.168.1.1 force")
    

    More generally, as in here:

    cmd := exec.Command("/bin/sh", "-c", "command1 param1; command2 param2; command3; ...")
    err := cmd.Run()       
    

    See this example:

    sh := os.Getenv("SHELL") //fetch default shell
    //execute the needed command with `-c` flag
    cmd := exec.Command(sh, "-c ", `docker exec 9aa1124 ...`)
    

    Or this one, putting your commands in a string first:

    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条)

相关推荐 更多相似问题