execx is an ergonomic, fluent wrapper around Go’s `os/exec` package.
What execx is
execx is a small, explicit wrapper around os/exec. It keeps the exec.Cmd model but adds fluent construction and consistent result handling.
There is no shell interpolation. Arguments, environment, and I/O are set directly, and nothing runs until you call Run, Output, or Start.
The core contract is deliberately narrow:
- a non-zero child exit is data in
Result.ExitCode, not a Go error;
- start, context, and I/O failures are returned as errors and mirrored in
Result.Err;
- a
Cmd is mutable and must not be configured or executed concurrently;
- output callbacks and caller-provided writers are serialized within one pipeline;
- strings shown by
String, ShellEscaped, and ShadowPrint are for display only and are never executed by a shell.
Installation
execx requires Go 1.27 or newer. Projects on older Go releases can pin the v1.1 release line.
go get github.com/goforj/execx
Quick Start
out, _ := execx.Command("echo", "hello").OutputTrimmed()
fmt.Println(out)
// #string hello
On Windows, use cmd /c echo hello or powershell -Command "echo hello" for shell built-ins.
Basic usage
Build a command and run it:
cmd := execx.Command("echo").Arg("hello")
res, _ := cmd.Run()
fmt.Print(res.Stdout)
// hello
Arguments are appended deterministically and never shell-expanded.
Output handling
Use Output variants when you only need stdout:
out, _ := execx.Command("echo", "hello").OutputTrimmed()
fmt.Println(out)
// #string hello
Output, OutputBytes, OutputTrimmed, and CombinedOutput differ only in how they return data.
Pipelining
Pipelines run on all platforms; command availability is OS-specific.
out, _ := execx.Command("printf", "go").
Pipe("tr", "a-z", "A-Z").
OutputTrimmed()
fmt.Println(out)
// #string GO
On Windows, use cmd /c or powershell -Command for shell built-ins.
Every stage is started concurrently. PipeStrict (default) selects the first stage with an execution error or non-zero exit as the primary result. PipeBestEffort selects the last stage and surfaces the first execution error. Neither mode turns a non-zero exit into a Go error.
Configuration is stage-local. Configure a stage before calling Pipe, then configure the returned stage separately:
first := execx.Command("producer").Env("ROLE=producer")
second := first.Pipe("consumer").Env("ROLE=consumer")
res, err := second.Run()
PipeStrict, PipeBestEffort, WithPTY, and shadow-print settings are chain-wide.
Context & cancellation
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
res, _ := execx.Command("go", "env", "GOOS").WithContext(ctx).Run()
fmt.Println(res.ExitCode == 0)
// #bool true
Contexts are stage-local in pipelines. Replacing WithTimeout or WithDeadline keeps the context supplied through WithContext as the parent, including an already-canceled parent.
Environment & I/O control
Environment is explicit and deterministic:
cmd := execx.Command("echo", "hello").Env("MODE=prod")
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// #bool true
Standard input is opt-in:
out, _ := execx.Command("cat").
StdinString("hi").
OutputTrimmed()
fmt.Println(out)
// #string hi
StdinBytes copies its input. OnStdout and OnStderr receive complete lines, including a final line without a trailing newline. A failure from StdoutWriter or StderrWriter is returned as ErrExec; bytes received before that failure remain available in Result.
Advanced features
For process control, use Start with the Process helpers:
proc := execx.Command("go", "env", "GOOS").Start()
res, _ := proc.Wait()
fmt.Println(res.ExitCode == 0)
// #bool true
Signals, timeouts, and OS controls are documented in the API section below.
ShadowPrint is available for emitting the command line before and after execution.
Kitchen Sink Chaining Example
// Run executes the command and returns the result and any error.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
res, err := execx.
Command("printf", "hello\nworld\n").
Pipe("tr", "a-z", "A-Z").
Env("MODE=demo").
WithContext(ctx).
OnStdout(func(line string) {
fmt.Println("OUT:", line)
}).
OnStderr(func(line string) {
fmt.Println("ERR:", line)
}).
Run()
if !res.OK() {
log.Fatalf("command failed: %v", err)
}
fmt.Printf("Stdout: %q\n", res.Stdout)
fmt.Printf("Stderr: %q\n", res.Stderr)
fmt.Printf("ExitCode: %d\n", res.ExitCode)
fmt.Printf("Error: %v\n", res.Err)
fmt.Printf("Duration: %v\n", res.Duration)
// OUT: HELLO
// OUT: WORLD
// Stdout: "HELLO\nWORLD\n"
// Stderr: ""
// ExitCode: 0
// Error: <nil>
// Duration: 10.123456ms
Error handling model
execx returns two error surfaces:
-
err (from Run, Output, CombinedOutput, Wait, etc) only reports execution failures:
- start failures (binary not found, not executable, OS start error)
- context cancellations or timeouts (
WithContext, WithTimeout, WithDeadline)
- output capture, callback writer, and caller-provided writer failures
- pipeline failures based on
PipeStrict / PipeBestEffort
-
Result.Err mirrors err for convenience; it is not for exit status.
Exit status is always reported via Result.ExitCode, even on non-zero exits. A non-zero exit does not automatically produce err.
Use err when you want to handle execution failures, and check Result.ExitCode (or Result.OK() / Result.IsExitCode) when you care about command success.
Security and logging
Command(name, args...) invokes the executable directly. It does not parse shell syntax, expand variables, glob paths, or interpret redirections. If you explicitly run a shell such as sh -c or bash -c, the command string becomes subject to that shell's rules and must be treated as untrusted input.
ShadowPrint can expose arguments. Use WithMask for secrets. Custom formatters receive both masked ShadowEvent.Command and unmasked ShadowEvent.RawCommand; avoid logging the raw value.
Compatibility notes
The v1 API and its non-zero-exit contract remain unchanged. This quality pass tightens four cases that were previously lossy or unsafe:
- final unterminated output is now delivered to line callbacks;
- caller-provided writer and PTY copy failures now return
ErrExec;
StdinBytes no longer observes later mutations of the caller's slice;
- replacement timeouts and deadlines no longer detach from their original parent context.
Code that intentionally depended on one of those edge behaviors should update before adopting the next release. No exported signature changed.
Non-goals and design principles
Design principles:
- Explicit over implicit
- No shell interpolation
- Composable, deterministic behavior
Non-goals:
- Shell scripting replacement
- Command parsing or glob expansion
- Task runners or build systems
- Automatic retries or heuristics
All public APIs are covered by runnable examples under ./examples, and the test suite executes them to keep docs and behavior in sync.
API Index