Run a command and capture output
Run a command and capture its output in Go with exec.Command(...).Output(). On failure the error is an *exec.ExitError that carries the stderr text.
A Go program needs to run another command and read what it printed, including the error message when it fails.
package main
import (
"errors"
"fmt"
"os/exec"
)
func main() {
out, err := exec.Command("echo", "hello").Output()
fmt.Printf("out=%q err=%v\n", out, err)
_, err = exec.Command("ls", "/nonexistent").Output()
var ee *exec.ExitError
if errors.As(err, &ee) {
fmt.Printf("exit=%d stderr=%q\n", ee.ExitCode(), ee.Stderr)
}
}go run main.goout="hello\n" err=<nil>
exit=2 stderr="ls: cannot access '/nonexistent': No such file or directory\n"Output runs the command, waits and returns what it wrote to standard output. If the command exits non-zero, the error is an *exec.ExitError, and when Stderr was not set Output fills the error's Stderr field with the beginning of what the command wrote there, as the os/exec documentation states. ExitCode gives the status. No shell is involved, so the arguments are passed exactly as written.
There is no shell, so pipes, globs and ~ in the arguments are not expanded. Use exec.Command("sh", "-c", ...) when you need them, and never put user input in that string. Only the first part of stderr is kept in the error, so set cmd.Stderr yourself when you need all of it.