How to Capture stdout and stderr from External Commands in Go

Capture stdout and stderr from external commands in Go by redirecting them to bytes.Buffer instances before running the command.

Use exec.Command to run the external command, then assign cmd.Stdout and cmd.Stderr to &bytes.Buffer instances before calling cmd.Run() to capture the output.

package main

import (
	"bytes"
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("ls", "-l")
	var outBuf, errBuf bytes.Buffer
	cmd.Stdout = &outBuf
	cmd.Stderr = &errBuf

	if err := cmd.Run(); err != nil {
		fmt.Println("Error:", err)
	}

	fmt.Println("Output:", outBuf.String())
	fmt.Println("Errors:", errBuf.String())
}