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())
}
Capturing stdout and stderr from external commands in Go lets your program run a system command and save its text output directly into memory instead of printing it to the screen. Think of it like holding a notepad under a printer to catch the paper as it comes out, so you can read or process the results later. You use it whenever you need to analyze what a command printed or log its errors without cluttering the console.