package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("ls", "/invalid-directory") errPipe, _ := cmd.StderrPipe() if err := cmd.Start(); err != nil { fmt.Println(err) return } errBuf := make([]byte, 1024) _, err := errPipe.Read(errBuf) if err == nil { fmt.Println(string(errBuf)) } cmd.Wait() }
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("echo", "hello world") cmd.Stderr = &myWriter{} if err := cmd.Run(); err != nil { fmt.Println(err) return } } type myWriter struct{} func (w *myWriter) Write(p []byte) (int, error) { fmt.Println("error occurred:", string(p)) return len(p), nil }In this example, we create a command to echo "hello world". We set the `Cmd.Stderr` field to a custom writer (`myWriter`) that we define. The `myWriter` writer simply prints out any data that is written to it prefixed with "error occurred:". When we run the command, any error output will be written to our custom writer. The `os/exec` package is a standard package library included with Go.