-6

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.

Biffen
  • 6,249
  • 6
  • 28
  • 36
sampat nayak
  • 123
  • 2
  • 12
  • 1
    It looks like you only want to execute a _single_ command, `docker`, with some arguments. Or which is the second command?! – Biffen Jul 02 '19 at 06:35
  • 2
    You can execute multiple commands with `exec.Command` by calling `exec.Command` more than once. If you're trying to pipe data between commands, like in the shell, you have to do that manually. But I don't see any evidence that you're trying to even execute two commands, let alone pipe them together. What is your actual problem? – Jonathan Hall Jul 02 '19 at 07:20
  • When i will try to execute. Output: exit status 127: docker exec requires at least 2 argument – sampat nayak Jul 02 '19 at 07:23
  • 4
    So pass two arguments. That has nothing to do with two commands. – Jonathan Hall Jul 02 '19 at 07:30

3 Answers3

3

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)
}
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
-1

multipass exec kube-node-one -- bash -c "ls && ls -a"

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the [help center](https://stackoverflow.com/help/how-to-answer). – Ethan Sep 24 '22 at 18:28
-2

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

No.

Volker
  • 40,468
  • 7
  • 81
  • 87