2019-07-02 04:34



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 ", "", " 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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongqu4443 dongqu4443 2年前

    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 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)
    点赞 评论 复制链接分享
  • duanlu7680 duanlu7680 2年前

    Is there any way we can execute a multiple commands in exec.Command


    点赞 评论 复制链接分享