Exec Exit Code And Stderr Capture

cmd.Output takes only stdout, so stderr needs its own buffer: non-zero exits wrap in *exec.ExitError whose ExitCode reports the concrete status.

GoCli Tooling

Code

gosnippet
34 lines
package main

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

func run(name string, args ...string) {
	cmd := exec.Command(name, args...)
	var stderr bytes.Buffer
	cmd.Stderr = &stderr // Output 只接管 stdout,stderr 需要自己接住

	out, err := cmd.Output()
	if err == nil {
		fmt.Printf("ok: %s\n", strings.TrimSpace(string(out)))
		return
	}

	// 非零退出码包装在 *exec.ExitError 里,ExitCode 给出具体码值
	var exitErr *exec.ExitError
	if errors.As(err, &exitErr) {
		fmt.Printf("exit=%d stderr=%s\n", exitErr.ExitCode(), strings.TrimSpace(stderr.String()))
		return
	}
	fmt.Println("not started:", err)
}

func main() {
	run("go", "version")              // 正常命令:stdout 有内容
	run("go", "doc", "fmt.NotAThing") // 失败命令:非零退出码 + stderr
}

How the snippet works

The snippet is organized around the functions run and main.

Watch out for

  • Zero third-party dependencies — the runtime provides every API used here.

Putting it to use

Entry signature: func run(name string, args ...string)

The run tags its output — ok:, exit=, not started: — when the file runs.

Running the file executes main, which drives run in order.

Core lines

if errors.As(err, &exitErr) {
	fmt.Printf("exit=%d stderr=%s\n", exitErr.ExitCode(), strings.TrimSpace(stderr.String()))
	return
}
func main() {
	run("go", "version")              // 正常命令:stdout 有内容
	run("go", "doc", "fmt.NotAThing") // 失败命令:非零退出码 + stderr
}

Interactive Tools for This Topic

FAQ

What does Exec Exit Code And Stderr Capture print when run?
The script runs standalone; its 3 labeled outputs include `ok:`, `exit=`, `not started:`.