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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.