Essential Go  Edit on GitHub      File Issue

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:

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.10 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.10 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