Executing commands

suggest change

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.13.4 linux/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.13.4 linux/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 the command as a new OS process. That process runs concurrently with this one.

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

Timing out process execution

os.Exec pitfalls

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents