Skip to content

Process Library for Go ​

process logo

Run commands, stream output, and manage subprocesses in Go.

Go ReferenceLicense: MITGo TestGo versionVersionPublished GitHub release countUnit coverageTests (Linux CI)

Quick Start · Examples · Behavior · API

Installation ​

Requires Go 1.27 or newer. Install Process in your Go module:

sh
go get github.com/goforj/process

Quick Start ​

Save this program as main.go in the same module, then run go run .:

go
package main

import (
	"fmt"
	"log"

	"github.com/goforj/process"
)

// main prints the installed Go version.
func main() {
	result, err := process.Command("go", "version").Run()
	if err != nil {
		log.Fatal(err)
	}

	// A command's exit status is separate from an execution error.
	if !result.OK() {
		log.Fatalf("go exited with status %d: %s", result.ExitCode, result.Stderr)
	}
	fmt.Print(result.Stdout)
}

Reuse settings across commands with a Runner. See execution and logging behavior for timeouts, exit handling, and application tests.

Runnable Examples ​

The testing example shows dependency injection and recorded commands. Browse the complete programs for JSON decoding, streaming output, background execution, and pipelines.

API Index ​

GroupFunctions
ConstructionCommand
RunnerNewRunner · Runner.Run
Testingprocesstest.Fake
ExecutionRun · OutputTrimmed · Start
ContextWithContext · WithTimeout
OS ControlsWithProcessTree
EnvironmentEnv · EnvOnly
InputStdinString
StreamingOnStdout · StdoutWriter
OutputDisableBuffering
DecodingDecodeJSON · DecodeYAML · As · Into
PipeliningPipe · PipelineResults
ProcessDone · Wait · PID · GracefulShutdown
ResultsOK · IsExitCode · EnsureSuccessful
Shadow PrintShadowPrint · WithMask

See the complete API documentation for every exported type and method.

Arguments ​

Arg ​

Arg appends arguments to the command.

go
cmd := process.Command("printf").Arg("hello")
out, err := cmd.Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

Construction ​

Command ​

Command constructs a new command without executing it.

go
cmd := process.Command("printf", "hello")
out, err := cmd.Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

Context ​

WithContext ​

WithContext binds the command to a context. A nil context is normalized to context.Background when execution begins.

go
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
res, err := process.Command("go", "env", "GOOS").WithContext(ctx).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

WithDeadline ​

WithDeadline binds the command to a deadline. Replacing a deadline retains the context previously supplied through WithContext as its parent.

go
res, err := process.Command("go", "env", "GOOS").WithDeadline(time.Now().Add(2 * time.Second)).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

WithTimeout ​

WithTimeout binds the command to a timeout. Replacing a timeout retains the context previously supplied through WithContext as its parent.

go
res, err := process.Command("go", "env", "GOOS").WithTimeout(2 * time.Second).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

Debugging ​

Args ​

Args returns the argv slice used for execution.

go
cmd := process.Command("go", "env", "GOOS")
fmt.Println(strings.Join(cmd.Args(), " "))
// Output:
// go env GOOS

ShellEscaped ​

ShellEscaped returns a shell-escaped string for logging only.

go
cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.ShellEscaped())
// Output:
// echo 'hello world' "it's"

String ​

String returns a human-readable representation of the command.

go
cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.String())
// Output:
// echo "hello world" it's

Decoding ​

As ​

As executes the command and decodes its selected output into T.

go
type Product struct {
	Name string `json:"name"`
}
product, err := process.Command("printf", `{"name":"Coffee"}`).DecodeJSON().As[Product]()
if err != nil {
	return err
}
fmt.Println(product.Name)
// Output:
// Coffee

Decode ​

Decode configures a custom decoder for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.

go
type payload struct {
	Name string
}
decoder := process.DecoderFunc(func(data []byte, dst any) error {
	out, ok := dst.(*payload)
	if !ok {
		return fmt.Errorf("expected *payload")
	}
	_, val, ok := strings.Cut(string(data), "=")
	if !ok {
		return fmt.Errorf("invalid payload")
	}
	out.Name = val
	return nil
})
var out payload
if err := process.Command("printf", "name=gopher").
	Decode(decoder).
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecodeJSON ​

DecodeJSON configures JSON decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecodeWith ​

DecodeWith executes the command and decodes stdout into dst.

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeWith(&out, process.DecoderFunc(json.Unmarshal)); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecodeYAML ​

DecodeYAML configures YAML decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.

go
type payload struct {
	Name string `yaml:"name"`
}
var out payload
if err := process.Command("printf", "name: gopher").
	DecodeYAML().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecoderFunc.Decode ​

Decode implements Decoder.

go
decoder := process.DecoderFunc(json.Unmarshal)
var product struct {
	Name string `json:"name"`
}
if err := decoder.Decode([]byte(`{"name":"Coffee"}`), &product); err != nil {
	return err
}
fmt.Println(product.Name)
// Output:
// Coffee

FromCombined ​

FromCombined decodes from combined stdout+stderr.

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}'`).
	DecodeJSON().
	FromCombined().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

FromStderr ​

FromStderr decodes from stderr.

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}' 1>&2`).
	DecodeJSON().
	FromStderr().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

FromStdout ​

FromStdout decodes from stdout (default).

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	FromStdout().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

Into ​

Into executes the command and decodes into dst.

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

Trim ​

Trim trims whitespace before decoding.

go
type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", "  {\"name\":\"gopher\"}  ").
	DecodeJSON().
	Trim().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

Environment ​

Env ​

Env adds environment variables to the command.

go
cmd := process.Command("go", "env", "GOOS").Env("MODE=prod")
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// Output:
// true

EnvAppend ​

EnvAppend merges variables into the inherited environment.

go
cmd := process.Command("go", "env", "GOOS").EnvAppend(map[string]string{"A": "1"})
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "A=1"))
// Output:
// true

EnvInherit ​

EnvInherit restores default environment inheritance.

go
cmd := process.Command("go", "env", "GOOS").EnvInherit()
fmt.Println(len(cmd.EnvList()) > 0)
// Output:
// true

EnvList ​

EnvList returns the environment list for execution.

go
cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1

EnvOnly ​

EnvOnly ignores the parent environment.

go
cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1

Errors ​

Error ​

Error returns the wrapped error message when available.

go
err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Error())
// Output:
// boom

ExitError.Error ​

Error reports the exit status without including potentially sensitive output.

go
err := process.ExitError{Result: process.Result{ExitCode: 7}}
fmt.Println(err.Error())
// Output:
// process: command exited with status 7

TimeoutError.Error ​

Error distinguishes inactivity from an elapsed total deadline.

go
err := process.TimeoutError{Idle: true}
fmt.Println(err.Error())
// Output:
// process: idle timeout exceeded

TimeoutError.Unwrap ​

Unwrap makes timeouts recognizable through errors.Is with context.DeadlineExceeded.

go
err := process.TimeoutError{}
fmt.Println(errors.Is(err.Unwrap(), context.DeadlineExceeded))
// Output:
// true

Unwrap ​

Unwrap exposes the underlying error.

go
err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Unwrap() != nil)
// Output:
// true

Execution ​

CombinedOutput ​

CombinedOutput executes the command and returns stdout and stderr in observed chunk order plus any execution error. Exact byte interleaving between the two operating-system streams is inherently scheduler-dependent.

go
output, err := process.Command("sh", "-c", "printf warning >&2").CombinedOutput()
if err != nil {
	return err
}
fmt.Println(output)
// Output:
// warning

OnExecCmd ​

OnExecCmd registers a callback to mutate the underlying exec.Cmd before process attaches its stdin, output capture, and pipeline wiring. Use it for fields such as SysProcAttr; process owns Stdin, Stdout, and Stderr during execution.

go
result, err := process.Command("go", "version").OnExecCmd(func(cmd *exec.Cmd) {
	cmd.WaitDelay = time.Second
}).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Output ​

Output executes the command and returns stdout and any error.

go
out, err := process.Command("printf", "hello").Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

OutputBytes ​

OutputBytes executes the command and returns stdout bytes and any error.

go
out, err := process.Command("printf", "hello").OutputBytes()
if err != nil {
	return err
}
fmt.Println(string(out))
// Output:
// hello

OutputTrimmed ​

OutputTrimmed executes the command and returns trimmed stdout and any error.

go
out, err := process.Command("printf", "hello\n").OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hello

Run ​

Run executes the command and returns the result and any execution error. A non-zero exit code is represented in Result and does not itself produce an error.

go
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

Start ​

Start executes the command asynchronously. Startup still completes synchronously, so a returned Process represents either a fully started pipeline or a completed error.

go
proc := process.Command("go", "env", "GOOS").Start()
res, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

Input ​

StdinBytes ​

StdinBytes sets stdin from a copy of bytes so later caller mutation cannot change the command input.

go
out, err := process.Command("cat").
	StdinBytes([]byte("hi")).
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

StdinFile ​

StdinFile sets stdin from a file.

go
file, err := os.CreateTemp("", "process-input-*")
if err != nil {
	return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteString("hello"); err != nil {
	return err
}
if _, err := file.Seek(0, 0); err != nil {
	return err
}
output, err := process.Command("cat").StdinFile(file).Output()
if err != nil {
	return err
}
fmt.Println(output)
// Output:
// hello

StdinReader ​

StdinReader sets stdin from an io.Reader.

go
out, err := process.Command("cat").
	StdinReader(strings.NewReader("hi")).
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

StdinString ​

StdinString sets stdin from a string.

go
out, err := process.Command("cat").
	StdinString("hi").
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

OS Controls ​

CreationFlags ​

CreationFlags is a no-op on non-Windows platforms; on Windows it sets process creation flags.

go
result, err := process.Command("go", "version").CreationFlags(process.CreateNewProcessGroup).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

HideWindow ​

HideWindow is a no-op on non-Windows platforms; on Windows it hides console windows.

go
result, err := process.Command("go", "version").HideWindow(true).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Pdeathsig ​

Pdeathsig signals the child when its creating OS thread exits on Linux. It is a no-op on other platforms.

go
out, err := process.Command("printf", "ok").Pdeathsig(syscall.SIGTERM).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

Setpgid ​

Setpgid places the child in a new process group for group signals.

go
out, err := process.Command("printf", "ok").Setpgid(true).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

Setsid ​

Setsid starts the child in a new session, detaching it from the terminal.

go
out, err := process.Command("printf", "ok").Setsid(true).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

WithProcessTree ​

WithProcessTree includes descendants when canceling or terminating a command. It owns a process group on Linux and macOS and a job object on Windows. Surviving members are terminated when the direct child exits. Unix children that create another group or session leave this scope. Unsupported platforms return an error before starting the command. The option applies to every stage in a pipeline and preserves the default behavior of other commands.

go
result, err := process.Command("go", "version").WithProcessTree().Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Output ​

DisableBuffering ​

DisableBuffering stops retaining this stage's stdout and stderr in results. Custom writers, callbacks, and pipeline connections still receive output. CombinedOutput also returns no captured bytes for this stage. Line callbacks retain an unfinished line until its newline or the end of the stream.

go
var output strings.Builder
result, err := process.Command("go", "env", "GOOS").
	StdoutWriter(&output).
	DisableBuffering().
	Run()
if err != nil {
	return err
}
fmt.Println("streamed:", output.Len() > 0, "captured bytes:", len(result.Stdout))
// Output:
// streamed: true captured bytes: 0

Pipelining ​

Pipe ​

Pipe appends a new command to the pipeline. Pipelines run on all platforms. Configuration called on the returned Cmd applies to the new stage; configure the current stage before Pipe when it needs different environment, context, or I/O.

go
out, err := process.Command("printf", "go").
	Pipe("tr", "a-z", "A-Z").
	OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// GO

PipeBestEffort ​

PipeBestEffort selects the last stage as the primary result while surfacing the first execution error. Every stage is started concurrently.

go
res, err := process.Command("false").
	Pipe("printf", "ok").
	PipeBestEffort().
	Run()
if err != nil {
	return err
}
fmt.Print(res.Stdout)
// Output:
// ok

PipeStrict ​

PipeStrict selects the first stage with an execution error or non-zero exit as the primary result. Every stage is still started concurrently.

go
res, err := process.Command("false").
	Pipe("printf", "ok").
	PipeStrict().
	Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode != 0)
// Output:
// true

PipelineResults ​

PipelineResults executes the command and returns per-stage results and the first execution error. Non-zero exit codes remain data in their corresponding Result.

go
results, err := process.Command("printf", "go").Pipe("tr", "a-z", "A-Z").PipelineResults()
if err != nil {
	return err
}
fmt.Println(results[0].Stdout, results[1].Stdout)
// Output:
// go GO

Process ​

Done ​

Done returns a channel that closes after all pipeline stages exit and their output is collected. Wait can then retrieve the immutable result without blocking.

go
proc := process.Command("go", "env", "GOOS").Start()
<-proc.Done()
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

GracefulShutdown ​

GracefulShutdown sends a signal and escalates to kill after the timeout.

go
proc := process.Command("sleep", "10").Start()
if err := proc.GracefulShutdown(os.Interrupt, time.Second); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

Interrupt ​

Interrupt sends an interrupt signal to the process.

go
proc := process.Command("sleep", "10").Start()
if err := proc.Interrupt(); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

KillAfter ​

KillAfter terminates the process after the given duration.

go
proc := process.Command("sleep", "10").Start()
proc.KillAfter(100 * time.Millisecond)
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

PID ​

PID returns the first pipeline stage's assigned process ID, or zero if no stage started. The ID remains available after completion and can be reused by the OS.

go
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(proc.PID() > 0)
// Output:
// true

PIDs ​

PIDs returns an independent slice of assigned process IDs in pipeline order. IDs describe started stages, including stages that have already exited.

go
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(len(proc.PIDs()))
// Output:
// 1

Running ​

Running reports whether a started pipeline is still collecting its result. It returns false for an unstarted handle and after Done closes.

go
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(proc.Running())
// Output:
// false

Send ​

Send sends a signal to the process.

go
proc := process.Command("sleep", "10").Start()
if err := proc.Send(os.Interrupt); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

Terminate ​

Terminate kills the process immediately.

go
proc := process.Command("sleep", "10").Start()
if err := proc.Terminate(); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

Wait ​

Wait waits for the command to complete and returns the result and any error.

go
proc := process.Command("go", "version").Start()
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Results ​

EnsureSuccessful ​

EnsureSuccessful returns the execution error or an ExitError for a nonzero status. It returns nil for success and does not change the Result.

go
result, err := process.Command("go", "version").Run()
if err != nil {
	return err
}
fmt.Println(result.EnsureSuccessful() == nil)
// Output:
// true

IsExitCode ​

IsExitCode reports whether the exit code matches.

go
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.IsExitCode(0))
// Output:
// true

IsSignal ​

IsSignal reports whether the command terminated due to a signal.

go
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.IsSignal(os.Interrupt))
// Output:
// false

OK ​

OK reports whether the command exited cleanly without errors.

go
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.OK())
// Output:
// true

Runner ​

NewRunner ​

NewRunner returns reusable settings without starting a process.

go
runner := process.NewRunner().Timeout(5 * time.Second).CheckExit()
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.CheckExit ​

CheckExit returns a Runner that reports a nonzero child exit as an ExitError. The default keeps nonzero exits in Result.ExitCode without returning an error.

go
_, err := process.NewRunner().CheckExit().Run(context.Background(), "sh", "-c", "exit 7")
var exit *process.ExitError
if !errors.As(err, &exit) {
	return err
}
fmt.Println(exit.Result.ExitCode)
// Output:
// 7

Runner.Dir ​

Dir returns a Runner using path as each child's working directory.

go
result, err := process.NewRunner().Dir(os.TempDir()).Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.DisableBuffering ​

DisableBuffering returns a Runner that streams output without retaining it.

go
var output strings.Builder
result, err := process.NewRunner().Stdout(&output).DisableBuffering().
	Run(context.Background(), "printf", "ready")
if err != nil {
	return err
}
fmt.Println(output.String(), len(result.Stdout))
// Output:
// ready 0

Runner.Env ​

Env returns a Runner with one environment override. An empty value sets an empty variable; use UnsetEnv to remove a variable from the child environment.

go
result, err := process.NewRunner().Env("MODE", "production").Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.Contains(result.Stdout, "MODE=production"))
// Output:
// true

Runner.IdleTimeout ​

IdleTimeout returns a Runner that cancels after d without stdout or stderr activity. Any nonempty output chunk resets the limit, even without a newline. A nonpositive duration disables this limit.

go
_, err := process.NewRunner().IdleTimeout(time.Second).Run(context.Background(), "sleep", "10")
var timeout *process.TimeoutError
fmt.Println(errors.As(err, &timeout) && timeout.Idle)
// Output:
// true

Runner.Input ​

Input returns a Runner that supplies a fresh reader of input to each child.

go
result, err := process.NewRunner().Input("request").Run(context.Background(), "cat")
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// request

Runner.Run ​

Run executes a fresh command using these settings. Arguments are passed directly to the executable. A nil context is treated as context.Background.

go
runner := process.NewRunner().Env("GOTOOLCHAIN", "local")
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.Start ​

Start starts a fresh command and reports startup failures immediately. The returned handle supports the existing Process lifecycle methods. Its Wait result follows this Runner's timeout and CheckExit policies.

go
child, err := process.NewRunner().Start(context.Background(), "go", "version")
if err != nil {
	return err
}
result, err := child.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.Stderr ​

Stderr returns a Runner that streams stderr to w as well as capturing it. The caller owns w. A nil writer disables streaming.

go
var output strings.Builder
result, err := process.NewRunner().Stderr(&output).Run(context.Background(), "sh", "-c", "printf warning >&2")
if err != nil {
	return err
}
fmt.Println(output.String(), result.Stderr)
// Output:
// warning warning

Runner.Stdout ​

Stdout returns a Runner that streams stdout to w as well as capturing it. The caller owns w. A nil writer disables streaming.

go
var output strings.Builder
result, err := process.NewRunner().Stdout(&output).Run(context.Background(), "printf", "ready")
if err != nil {
	return err
}
fmt.Println(output.String(), result.Stdout)
// Output:
// ready ready

Runner.Timeout ​

Timeout returns a Runner with a total limit starting at each Run or Start call. A nonpositive duration disables this limit. The caller's context still applies.

go
result, err := process.NewRunner().Timeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.UnsetEnv ​

UnsetEnv returns a Runner that removes key from each child's environment.

go
result, err := process.NewRunner().Env("EXAMPLE_TOKEN", "test").UnsetEnv("EXAMPLE_TOKEN").
	Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.Contains(result.Stdout, "EXAMPLE_TOKEN="))
// Output:
// false

Runner.WaitDelay ​

WaitDelay returns a Runner that bounds output-pipe draining after the child exits or its context is canceled. A nonpositive duration leaves draining unlimited. This does not interrupt a caller-owned writer blocked in Write.

go
result, err := process.NewRunner().Timeout(5*time.Second).WaitDelay(time.Second).
	Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.WithProcessTree ​

WithProcessTree returns a Runner that includes descendants in cancellation and termination. The native ownership and platform limits match Cmd.WithProcessTree.

go
runner := process.NewRunner().WithProcessTree().Timeout(5 * time.Second)
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.WithoutInheritingEnv ​

WithoutInheritingEnv returns a Runner that starts with an empty environment. Explicit Env settings are retained. Executable lookup still uses the parent's PATH, as with os/exec; use an absolute program path to control lookup.

go
result, err := process.NewRunner().WithoutInheritingEnv().Env("MODE", "test").
	Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.TrimSpace(result.Stdout))
// Output:
// MODE=test

Shadow Print ​

ShadowOff ​

ShadowOff disables shadow printing for this command chain, preserving configuration.

go
result, err := process.Command("printf", "hello").ShadowPrint().ShadowOff().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

ShadowOn ​

ShadowOn enables shadow printing using the previously configured options.

go
cmd := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build"))
cmd.ShadowOff()
result, err := cmd.ShadowOn().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

ShadowPrint ​

ShadowPrint configures shadow printing for this command chain.

go
result, err := process.Command("printf", "hello").ShadowPrint().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

WithFormatter ​

WithFormatter sets a formatter for ShadowPrint output.

go
formatter := func(event process.ShadowEvent) string {
	return fmt.Sprintf("%s: %s", event.Phase, event.Command)
}
result, err := process.Command("printf", "hello").ShadowPrint(process.WithFormatter(formatter)).Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

WithMask ​

WithMask applies a masker to the shadow-printed command string.

go
mask := func(command string) string { return strings.ReplaceAll(command, "secret", "***") }
result, err := process.Command("printf", "secret").ShadowPrint(process.WithMask(mask)).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

WithPrefix ​

WithPrefix sets the shadow print prefix.

go
result, err := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build")).Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

Streaming ​

OnStderr ​

OnStderr registers a line callback for stderr. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline.

go
if _, err := process.Command("sh", "-c", "printf 'warning\\n' >&2").
	OnStderr(func(line string) { fmt.Println(line) }).Run(); err != nil {
	return err
}
// Output:
// warning

OnStdout ​

OnStdout registers a line callback for stdout. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline.

go
if _, err := process.Command("printf", "hi\n").
	OnStdout(func(line string) { fmt.Println(line) }).
	Run(); err != nil {
	return err
}
// Output:
// hi

StderrWriter ​

StderrWriter sets a raw writer for stderr.

When the writer is a terminal and no line callbacks or combined output are enabled, process passes stderr through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.

go
var output strings.Builder
if _, err := process.Command("sh", "-c", "printf warning >&2").StderrWriter(&output).Run(); err != nil {
	return err
}
fmt.Println(output.String())
// Output:
// warning

StdoutWriter ​

StdoutWriter sets a raw writer for stdout.

When the writer is a terminal and no line callbacks or combined output are enabled, process passes stdout through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.

go
var out strings.Builder
if _, err := process.Command("printf", "hello").
	StdoutWriter(&out).
	Run(); err != nil {
	return err
}
fmt.Print(out.String())
// Output:
// hello

WithPTY ​

WithPTY attaches stdout/stderr to a pseudo-terminal.

When enabled, stdout and stderr are merged into a single stream. OnStdout and OnStderr both receive the same lines, and Result.Stderr remains empty. Platforms without PTY support return an error when the command runs.

go
if _, err := process.Command("printf", "hi").
	WithPTY().
	OnStdout(func(line string) { fmt.Println(line) }).
	Run(); err != nil {
	return err
}
// Output:
// hi

Testing ​

processtest.Fake ​

Inject process.Executor into application code. Queue results on a separate fake for each test, then inspect its calls. Unexpected commands return an error and never start a real process.

go
status := func(ctx context.Context, commands process.Executor) (string, error) {
	result, err := commands.Run(ctx, "git", "status", "--short")
	if err != nil {
		return "", err
	}
	if err := result.EnsureSuccessful(); err != nil {
		return "", err
	}
	return strings.TrimSpace(result.Stdout), nil
}
var fake processtest.Fake
fake.Queue(process.Result{Stdout: " M README.md\n"})
output, err := status(context.Background(), &fake)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(output)

call := fake.Calls()[0]
fmt.Println(call.Name, strings.Join(call.Args, " "))

_, err = fake.Run(context.Background(), "unexpected-command")
fmt.Println(errors.Is(err, processtest.ErrUnexpectedCommand))
// Output:
// M README.md
// git status --short
// true

WorkingDir ​

Dir ​

Dir sets the working directory.

go
dir, err := filepath.EvalSymlinks(os.TempDir())
if err != nil {
	return err
}
out, err := process.Command("pwd").Dir(dir).OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out == dir)
// Output:
// true

Development ​

sh
make test          # Run library, generator, and example tests.
make vet           # Check all three Go modules.
make test-examples # Execute examples and check their output.
make test-race     # Check library tests for data races.
make generate   # Regenerate examples and the API reference from GoDoc.

The example suite executes every program and checks its output on Unix. Windows runs the portable Go-command examples and compiles the Unix-specific programs.

Edit the GoDoc examples or the tested fake example before regenerating. The docs and examples modules keep tooling out of the library's module download. Use make help for more commands.

For an existing application, see the migration guide.

Licensed under the MIT License.