Essential Go  Suggest an edit

Executing commands

Package exec in standard library is a cross-platform way to launch processes, capture their output and more.

Basic command execution

The simplest usage is: * create exec.Cmd struct using exec.Command(exe string, args ...string) * call cmd.CombinedOutput() to execute the cmd and get combined stdout and stderr * to get only stdout, call cmd.Output()

cmd := exec.Command("go", "version")
out, err := cmd.CombinedOutput()
if err != nil {
	log.Fatalf("cmd.CombinedOutput() failed with '%s'\n", err)
}
fmt.Printf("Output:\n%s\n", string(out))
Output:
go version go1.11.1 darwin/amd64

More advanced command execution

var stdout, stderr bytes.Buffer
cmd := exec.Command("go", "version")
cmd.Stdout = &stdout
cmd.Stderr = &stderr

err := cmd.Start()
if err != nil {
	log.Fatalf("cmd.Start() failed with '%s'\n", err)
}

err = cmd.Wait()
if err != nil {
	log.Fatalf("cmd.Wait() failed with '%s'\n", err)
}
out := append(stdout.Bytes(), stderr.Bytes()...)
fmt.Printf("Output:\n%s\n", string(out))
Output:
go version go1.11.1 darwin/amd64

This is functionally the same as the above example but we use a more fine-grained control.

We capture stdout and stderr of the process by setting cmd.Stdout and cmd.Stderr to a memory-backed io.Writer.

cmd.Start()starts command as new OS process. It executes concurrently with our code, as OS processes do.

We need to call cmd.Wait() to wait for the process to finish. To prevent waiting infinitely, you might want to add a timeout.

  ↑ ↓ to navigate     ↵ to select     Esc to close