Run commands, stream output, and manage subprocesses in Go.
Quick Start · Examples · Behavior · API
Requires Go 1.27 or newer. Install Process in your Go module:
go get github.com/goforj/processSave this program as main.go in the same module, then run go run .:
package main
import (
"context"
"fmt"
"log"
"github.com/goforj/process"
)
// main prints the installed Go version.
func main() {
result, err := process.Run(context.Background(), "go", "version")
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)
}Chain settings with process.Timeout(...).Run(ctx, ...), or keep a Runner for repeated commands. See execution and logging behavior for execution details, or use the production guide for bounded commands, readiness, shutdown, and application tests.
Browse complete programs for JSON decoding, streaming output, background execution, and pipelines.
The testing example shows dependency injection and recorded commands. The configured import and its application test show how to inspect per-request settings before returning a scoped fake.
For service lifecycle and concurrency, use the preview service or concurrent build. Both include application tests.
| Group | Functions |
|---|---|
| Execution | Run · Start · OutputTrimmed |
| Runner | NewRunner · Runner.Run · Runner.Starter |
| Context | Timeout · IdleTimeout · WaitDelay · WithContext |
| Working Directory | Dir |
| Environment | Env · UnsetEnv · WithoutInheritingEnv |
| Input | Input · StdinString |
| Output | DisableBuffering · OutputLimit · LineLimit |
| Streaming | Stdout · Stderr · ObserveOutput · Chunks · WaitForOutput |
| Process | Done · Wait · Stop · PID |
| Results | CheckExit · Cmd.CheckExit · OK · IsExitCode · EnsureSuccessful |
| Testing | processtest.Fake · Runner.Settings · processtest.Fake.Respond · processtest.Fake.Start · processtest.Child.WaitForOutput |
| Groups | NewGroup · Group.Using · Group.FailFast · Group.Run |
| Construction | Command |
| Decoding | DecodeJSON · DecodeYAML · As · Into |
| Pipelining | Pipe · PipelineResults |
| OS Controls | WithProcessTree |
| Shadow Print | ShadowPrint · WithMask |
See the complete API documentation for every exported type and method.
Run executes a command with default settings and the caller's context. Arguments go directly to the executable. A nonzero exit remains result data.
result, err := process.Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueStart starts a command with default settings and reports startup failures immediately.
child, err := process.Start(context.Background(), "go", "version")
if err != nil {
return err
}
result, err := child.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// trueOutputTrimmed executes the command and returns trimmed stdout and any error.
out, err := process.Command("printf", "hello\n").OutputTrimmed()
if err != nil {
return err
}
fmt.Println(out)
// helloRun 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.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// trueStart executes the command asynchronously. Startup still completes synchronously, so a returned Process represents either a fully started pipeline or a completed error.
proc := process.Command("go", "env", "GOOS").Start()
res, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// trueCombinedOutput 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.
output, err := process.Command("sh", "-c", "printf warning >&2").CombinedOutput()
if err != nil {
return err
}
fmt.Println(output)
// warningOnExecCmd 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.
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())
// trueOutput executes the command and returns stdout and any error.
out, err := process.Command("printf", "hello").Output()
if err != nil {
return err
}
fmt.Print(out)
// helloOutputBytes executes the command and returns stdout bytes and any error.
out, err := process.Command("printf", "hello").OutputBytes()
if err != nil {
return err
}
fmt.Println(string(out))
// helloNewRunner returns reusable settings without starting a process.
runner := process.NewRunner().Env("GOTOOLCHAIN", "local").Timeout(5 * time.Second).CheckExit()
result, err := runner.Run(context.Background(), "go", "env", "GOTOOLCHAIN")
if err != nil {
return err
}
fmt.Print(result.Stdout)
// localRun executes a fresh command using these settings. Arguments are passed directly to the executable. A nil context is treated as context.Background.
runner := process.NewRunner().Env("GOTOOLCHAIN", "local")
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueStarter adapts these settings to the consumer-facing background contract. Runner.Start keeps returning *Process for callers that need native controls.
starter := process.Timeout(5 * time.Second).Starter()
child, err := starter.Start(context.Background(), "go", "version")
if err != nil {
return err
}
result, err := child.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// trueCheckExit returns a Runner that reports a nonzero child exit as an ExitError. The default keeps nonzero exits in Result.ExitCode without returning an error.
_, 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)
// 7Dir returns a Runner using path as each child's working directory.
result, err := process.NewRunner().Dir(os.TempDir()).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueDisableBuffering returns a Runner that streams output without retaining it.
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))
// ready 0Env returns a Runner with one environment override. An empty value sets an empty variable; use UnsetEnv to remove a variable from the child environment.
result, err := process.NewRunner().Env("MODE", "production").Run(context.Background(), "env")
if err != nil {
return err
}
fmt.Println(strings.Contains(result.Stdout, "MODE=production"))
// trueIdleTimeout 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.
_, err := process.NewRunner().IdleTimeout(time.Second).Run(context.Background(), "sleep", "10")
var timeout *process.TimeoutError
fmt.Println(errors.As(err, &timeout) && timeout.Idle)
// trueInput returns a Runner that supplies a fresh reader of input to each child.
result, err := process.NewRunner().Input("request").Run(context.Background(), "cat")
if err != nil {
return err
}
fmt.Println(result.Stdout)
// requestObserveOutput returns a runner that retains at most bytes for background observers. Result capture is independent. Nonpositive values disable observation. Slow readers receive ErrOutputLost; they never block the process or silently miss output.
child, err := process.NewRunner().ObserveOutput(4096).Start(context.Background(), "go", "version")
if err != nil {
return err
}
if err := child.WaitForOutput(context.Background(), "go version"); err != nil {
return err
}
_, err = child.Wait()
if err != nil {
return err
}
fmt.Println("version observed")
// version observedOutputLimit returns a runner with a combined stdout and stderr budget per invocation. Overflow stops the command, retains accepted output, and returns an OutputLimitError. A nonpositive limit is unlimited.
_, err := process.OutputLimit(4).Run(context.Background(), "go", "version")
var limit *process.OutputLimitError
fmt.Println(errors.As(err, &limit))
// trueStart 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.
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())
// trueStderr returns a Runner that streams stderr to w as well as capturing it. The caller owns w. A nil writer disables streaming.
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)
// warning warningStdout returns a Runner that streams stdout to w as well as capturing it. The caller owns w. A nil writer disables streaming.
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)
// ready readyTimeout returns a Runner with an execution deadline starting at each Run or Start call. A nonpositive duration disables this limit. The caller's context still applies. Use WaitDelay and WithProcessTree to bound inherited output-pipe lifetimes.
result, err := process.NewRunner().Timeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueUnsetEnv returns a Runner that removes key from each child's environment.
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="))
// falseWaitDelay 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.
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())
// trueWithProcessTree returns a Runner that includes descendants in cancellation and termination. The native ownership and platform limits match Cmd.WithProcessTree.
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())
// trueWithoutInheritingEnv 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.
result, err := process.NewRunner().WithoutInheritingEnv().Env("MODE", "test").
Run(context.Background(), "env")
if err != nil {
return err
}
fmt.Println(strings.TrimSpace(result.Stdout))
// MODE=testTimeout returns a runner with an execution deadline starting at each invocation. Use WaitDelay to bound inherited output-pipe draining. Settings are local to the returned value; no global configuration is changed.
result, err := process.Timeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueIdleTimeout returns a runner that stops after d without output. Settings are local to the returned value; no global configuration is changed.
result, err := process.IdleTimeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueWaitDelay returns a runner with bounded output-pipe draining. Settings are local to the returned value; no global configuration is changed.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, err := process.Timeout(5*time.Second).
WithProcessTree().
WaitDelay(250*time.Millisecond).
OutputLimit(1<<20).
CheckExit().
Env("GOTOOLCHAIN", "local").
Run(ctx, "go", "env", "GOTOOLCHAIN")
if err != nil {
return err
}
fmt.Print(result.Stdout)
// localWithContext binds the command to a context. A nil context is normalized to context.Background when execution begins.
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)
// trueWithDeadline sets an absolute deadline shared by repeated executions. Replacing a deadline retains the context previously supplied through WithContext as its parent.
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)
// trueWithTimeout sets a deadline measured from configuration time, shared by repeated executions. Replacing a timeout retains the context previously supplied through WithContext as its parent.
res, err := process.Command("go", "env", "GOOS").WithTimeout(2 * time.Second).Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode == 0)
// trueDir returns a runner using path as its working directory. Settings are local to the returned value; no global configuration is changed.
result, err := process.Dir(os.TempDir()).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueEnv returns a runner with one environment override. Settings are local to the returned value; no global configuration is changed.
result, err := process.Env("GOTOOLCHAIN", "local").Run(context.Background(), "go", "env", "GOTOOLCHAIN")
if err != nil {
return err
}
fmt.Println(strings.TrimSpace(result.Stdout) == "local")
// trueUnsetEnv returns a runner that removes key from the inherited environment. Settings are local to the returned value; no global configuration is changed.
result, err := process.UnsetEnv("PROCESS_EXAMPLE_UNUSED").Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueWithoutInheritingEnv returns a runner that inherits no environment variables. Settings are local to the returned value; no global configuration is changed.
result, err := process.WithoutInheritingEnv().Env("PATH", os.Getenv("PATH")).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueEnv adds environment variables to the command.
cmd := process.Command("go", "env", "GOOS").Env("MODE=prod")
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// trueEnvAppend merges variables into the inherited environment.
cmd := process.Command("go", "env", "GOOS").EnvAppend(map[string]string{"A": "1"})
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "A=1"))
// trueEnvInherit restores default environment inheritance.
cmd := process.Command("go", "env", "GOOS").EnvInherit()
fmt.Println(len(cmd.EnvList()) > 0)
// trueEnvList returns the environment list for execution.
cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// A=1EnvOnly ignores the parent environment.
cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// A=1Input returns a runner that supplies a fresh copy of input to each command. Settings are local to the returned value; no global configuration is changed.
result, err := process.Input("request").Run(context.Background(), "cat")
if err != nil {
return err
}
fmt.Println(result.Stdout)
// requestStdinString sets stdin from a string.
out, err := process.Command("cat").
StdinString("hi").
Output()
if err != nil {
return err
}
fmt.Println(out)
// hiStdinBytes sets stdin from a copy of bytes so later caller mutation cannot change the command input.
out, err := process.Command("cat").
StdinBytes([]byte("hi")).
Output()
if err != nil {
return err
}
fmt.Println(out)
// hiStdinFile sets stdin from a file.
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)
// helloStdinReader borrows an io.Reader without taking ownership of closing it. A blocked Read needs cancellation or closure controlled by the reader's owner. Execution deadlines and WaitDelay cannot interrupt arbitrary reader code.
out, err := process.Command("cat").
StdinReader(strings.NewReader("hi")).
Output()
if err != nil {
return err
}
fmt.Println(out)
// hiDisableBuffering returns a runner that streams output without retaining it. Settings are local to the returned value; no global configuration is changed.
result, err := process.DisableBuffering().Stdout(io.Discard).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(len(result.Stdout))
// 0OutputLimit returns a runner that stops after more than bytes of stdout and stderr. Settings are local to the returned value; no global configuration is changed.
_, err := process.OutputLimit(4).Run(context.Background(), "go", "version")
var limit *process.OutputLimitError
fmt.Println(errors.As(err, &limit))
// trueLineLimit stops the pipeline if a callback line exceeds bytes before its newline. It bounds OnStdout and OnStderr buffers, including PTY callbacks. The oversized line is not delivered as a truncated callback. A nonpositive limit is unlimited. Capture remains independently controlled by OutputLimit and DisableBuffering.
_, err := process.Command("go", "version").DisableBuffering().LineLimit(4).
OnStdout(func(line string) { fmt.Println(line) }).Run()
var limit *process.OutputLimitError
fmt.Println(errors.As(err, &limit) && limit.Line)
// trueDisableBuffering 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.
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))
// streamed: true captured bytes: 0OutputLimit stops the pipeline when this stage emits more than bytes across stdout and stderr. It retains and forwards the accepted prefix and returns an OutputLimitError. The limit also applies with DisableBuffering. A nonpositive limit is unlimited.
_, err := process.Command("go", "version").OutputLimit(4).Run()
var limit *process.OutputLimitError
fmt.Println(errors.As(err, &limit))
// trueError describes the exceeded budget without including command output.
err := &process.OutputLimitError{Limit: 4}
fmt.Println(err.Error())
// process: output exceeds 4 bytesStdout returns a runner that streams standard output to w while capturing it. Settings are local to the returned value; no global configuration is changed.
var output strings.Builder
result, err := process.Stdout(&output).Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(output.Len() > 0 && result.Stdout == output.String())
// trueStderr returns a runner that streams standard error to w while capturing it. Settings are local to the returned value; no global configuration is changed.
var output strings.Builder
// An invalid flag makes the Go tool write to stderr.
result, err := process.Stderr(&output).Run(context.Background(), "go", "version", "-invalid-flag")
if err != nil {
return err
}
fmt.Println(output.Len() > 0 && result.Stderr == output.String())
// trueObserveOutput creates fresh runner settings with bounded output observation.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
child, err := process.ObserveOutput(4096).Start(ctx, "go", "version")
if err != nil {
return err
}
if err := child.WaitForOutput(ctx, "go version"); err != nil {
return err
}
if _, err := child.Wait(); err != nil {
return err
}
fmt.Println("version observed")
// version observedChunks iterates from the start of this process's output with an independent cursor. Enable ObserveOutput before Start. Cancellation ends this reader without canceling execution. History loss is reported as ErrOutputLost. Completed history can be replayed.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
child, err := process.ObserveOutput(4096).DisableBuffering().Start(ctx, "go", "version")
if err != nil {
return err
}
var output strings.Builder
for chunk, err := range child.Chunks(ctx) {
if err != nil { return err }
output.WriteString(chunk.Text)
}
result, err := child.Wait()
if err != nil {
return err
}
fmt.Printf("version streamed: %t\ncaptured bytes: %d\n", strings.Contains(output.String(), "go version"), len(result.Stdout))
// version streamed: true
// captured bytes: 0WaitForOutput waits for text on one stage and stream, including split writes and output received before this call. It returns io.EOF if the process closes output without a match. A canceled wait does not cancel the process. The marker cannot exceed the observation byte budget. Output loss is always reported.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
child, err := process.ObserveOutput(4096).Start(ctx, "go", "version")
if err != nil {
return err
}
if err := child.WaitForOutput(ctx, "go version"); err != nil {
return err
}
if _, err := child.Wait(); err != nil {
return err
}
fmt.Println("output matched")
// output matchedObserveOutput enables bounded observation for the entire command pipeline. Configure it before Start. Nonpositive values disable observation.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
child := process.Command("go", "version").WithContext(ctx).ObserveOutput(4096).Start()
if err := child.WaitForOutput(ctx, "go version"); err != nil {
return err
}
if _, err := child.Wait(); err != nil {
return err
}
fmt.Println("version observed")
// version observedOnStderr 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.
if _, err := process.Command("sh", "-c", "printf 'warning\\n' >&2").
OnStderr(func(line string) { fmt.Println(line) }).Run(); err != nil {
return err
}
// warningOnStdout 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.
if _, err := process.Command("printf", "hi\n").
OnStdout(func(line string) { fmt.Println(line) }).
Run(); err != nil {
return err
}
// hiStderrWriter 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.
var output strings.Builder
if _, err := process.Command("sh", "-c", "printf warning >&2").StderrWriter(&output).Run(); err != nil {
return err
}
fmt.Println(output.String())
// warningStdoutWriter 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.
var out strings.Builder
if _, err := process.Command("printf", "hello").
StdoutWriter(&out).
Run(); err != nil {
return err
}
fmt.Print(out.String())
// helloWithPTY 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.
if _, err := process.Command("printf", "hi").
WithPTY().
OnStdout(func(line string) { fmt.Println(line) }).
Run(); err != nil {
return err
}
// hiDone returns a channel that closes after all pipeline stages exit and their output is collected. Wait can then retrieve the immutable result without blocking.
proc := process.Command("go", "env", "GOOS").Start()
<-proc.Done()
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// trueWait waits for the command to complete and returns the result and any error.
proc := process.Command("go", "version").Start()
result, err := proc.Wait()
if err != nil {
return err
}
fmt.Println(result.OK())
// trueStop requests portable shutdown, waits for grace, and then escalates to termination. Unix uses SIGTERM; other platforms use immediate termination. ctx bounds this call, including output collection. Cancellation also requests immediate termination. If collection outlives ctx, the returned result carries the context error; Wait can still collect the final result later. Caller-owned blocking readers and writers remain the caller's responsibility. A completed process returns its existing result.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
child, err := process.WithProcessTree().Start(ctx, "go", "version")
if err != nil {
return err
}
if _, err := child.Stop(ctx, time.Second); err != nil {
return err
}
fmt.Println("process stopped:", !child.Running())
// process stopped: truePID 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.
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
return err
}
fmt.Println(proc.PID() > 0)
// trueGracefulShutdown sends a signal and escalates to kill after the timeout.
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)
// trueInterrupt sends an interrupt signal to the process.
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)
// trueKillAfter terminates the process after the given duration.
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)
// truePIDs returns an independent slice of assigned process IDs in pipeline order. IDs describe started stages, including stages that have already exited.
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
return err
}
fmt.Println(len(proc.PIDs()))
// 1Running reports whether a started pipeline is still collecting its result. It returns false for an unstarted handle and after Done closes.
proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
return err
}
fmt.Println(proc.Running())
// falseSend sends a signal to the process.
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)
// trueTerminate kills the process immediately.
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)
// trueCheckExit returns a runner that reports nonzero exits as an ExitError. Settings are local to the returned value; no global configuration is changed.
result, err := process.CheckExit().Env("GOTOOLCHAIN", "local").Run(context.Background(), "go", "env", "GOTOOLCHAIN")
if err != nil {
return err
}
fmt.Print(result.Stdout)
// localCheckExit reports a nonzero selected exit status as an ExitError. The setting applies to the entire pipeline and to decoding, output, and background execution. PipeStrict checks the first failed stage; PipeBestEffort checks the last stage. A selected execution error takes priority over its exit status. PipelineResults keeps each stage's raw status.
type Toolchain struct {
Mode string `json:"GOTOOLCHAIN"`
}
toolchain, err := process.Command("go", "env", "-json", "GOTOOLCHAIN").
Env("GOTOOLCHAIN=local").
CheckExit().
DecodeJSON().As[Toolchain]()
if err != nil {
return err
}
fmt.Println(toolchain.Mode)
// localOK reports whether the command exited cleanly without errors.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.OK())
// trueIsExitCode reports whether the exit code matches.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.IsExitCode(0))
// trueEnsureSuccessful returns the execution error or an ExitError for a nonzero status. It returns nil for success and does not change the Result.
result, err := process.Command("go", "version").Run()
if err != nil {
return err
}
fmt.Println(result.EnsureSuccessful() == nil)
// trueIsSignal reports whether the command terminated due to a signal.
res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
return err
}
fmt.Println(res.IsSignal(os.Interrupt))
// falseWithSignal returns a copy with the supplied termination signal. It allows executors and test fakes to construct signal outcomes without changing exit status.
result := (process.Result{ExitCode: -1}).WithSignal(os.Kill)
fmt.Println("terminated:", result.IsSignal(os.Kill))
// terminated: trueInject 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.
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))
// M README.md
// git status --short
// trueSettings returns an independent configuration snapshot without starting a command or reading the inherited environment. Use it in application factories to verify execution policy before returning an Executor or Starter.
settings := process.Dir("imports").Env("MODE", "validate").
Input("product,price\nCoffee,12\n").Timeout(30*time.Second).CheckExit().Settings()
fmt.Println(settings.Dir, settings.Env["MODE"], settings.Timeout, settings.CheckExit)
// imports validate 30s trueMatch exact executable names and arguments to keep concurrent command responses deterministic.
var fake processtest.Fake
fake.Respond("importer", []string{"products.csv"}, process.Result{Stdout: "imported 3 products"})
fake.Respond("renderer", []string{"catalog"}, process.Result{Stdout: "rendered catalog"})
results, err := process.NewGroup(2).Using(&fake).Run(context.Background(), process.Invocation{Name: "importer", Args: []string{"products.csv"}}, process.Invocation{Name: "renderer", Args: []string{"catalog"}})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s\n%s\n", results[0].Stdout, results[1].Stdout)
// imported 3 products
// rendered catalogInject process.Starter to test background work. Queue a child, complete it under test control, and inspect recorded commands without starting a program.
launch := func(ctx context.Context, starter process.Starter) (process.Child, error) {
return starter.Start(ctx, "importer", "--source", "products.csv")
}
var fake processtest.Fake
child := new(processtest.Child)
fake.RespondStart("importer", []string{"--source", "products.csv"}, child, nil)
running, err := launch(context.Background(), &fake)
if err != nil {
fmt.Println(err)
return
}
child.Complete(process.Result{Stdout: "imported 3 rows"})
<-running.Done()
result, err := running.Wait()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Stdout, fake.Calls()[0].Name)
// imported 3 rows importerSupply readiness output and final outcomes without starting a real service.
child := processtest.NewChild(4096)
if err := child.Emit(process.OutputChunk{Stream: process.StdoutStream, Text: "listening on port 8080"}); err != nil {
fmt.Println(err)
return
}
if err := child.WaitForOutput(context.Background(), "listening"); err != nil {
fmt.Println(err)
return
}
child.Complete(process.Result{Stdout: "service stopped"})
result, err := child.Stop(context.Background(), 0)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("service ready\n%s\n", result.Stdout)
// service ready
// service stoppedNewGroup returns a group using default process settings. Concurrency must be positive; Run reports an invalid value before starting any commands.
results, err := process.NewGroup(2).Run(context.Background(),
process.Invocation{Name: "go", Args: []string{"version"}},
process.Invocation{Name: "go", Args: []string{"env", "GOOS"}},
)
if err != nil {
return err
}
fmt.Println(len(results), results[0].OK(), results[1].OK())
// 2 true trueUsing returns a group using executor for every command. Use a Runner to share settings or a scoped processtest.Fake in application tests.
results, err := process.NewGroup(2).Using(process.Env("GOTOOLCHAIN", "local").Timeout(5*time.Second).CheckExit()).
Run(context.Background(), process.Invocation{Name: "go", Args: []string{"env", "GOTOOLCHAIN"}})
if err != nil {
return err
}
fmt.Print(results[0].Stdout)
// localFailFast returns a group that cancels running commands and skips pending commands after the first execution error. Use CheckExit on the injected runner when a nonzero exit should trigger cancellation. The default collects all results.
results, err := process.NewGroup(1).Using(process.CheckExit()).FailFast().
Run(context.Background(),
process.Invocation{Name: "go", Args: []string{"process-example-missing-command"}},
process.Invocation{Name: "go", Args: []string{"version"}},
)
var failed *process.InvocationError
if !errors.As(err, &failed) {
return fmt.Errorf("expected a failed command, got %v", err)
}
fmt.Println("failed command index:", failed.Index)
// failed command index: 0
fmt.Println("pending command:", results[1].Err)
// pending command: context canceledRun executes at most the configured number of commands concurrently and waits for every started command. Results follow input order; their Err fields retain individual failures. The returned error joins InvocationError values in that same order, retaining each input index and requested command. Pending commands receive a cancellation result without invoking the executor. Nonzero exits remain data unless the executor reports them as errors.
results, err := process.NewGroup(1).Run(context.Background(), process.Invocation{Name: "go", Args: []string{"version"}})
if err != nil {
return err
}
fmt.Println(results[0].OK())
// trueError identifies the command without including potentially sensitive arguments.
failure := &process.InvocationError{Index: 1, Command: process.Invocation{Name: "importer"}, Err: errors.New("input unavailable")}
fmt.Println(failure.Error())
// process: command 1 (importer): input unavailableUnwrap preserves errors.Is and errors.As for the execution failure.
cause := errors.New("input unavailable")
failure := &process.InvocationError{Err: cause}
fmt.Println(failure.Unwrap() == cause)
// trueCommand constructs a new command without executing it.
cmd := process.Command("printf", "hello")
out, err := cmd.Output()
if err != nil {
return err
}
fmt.Print(out)
// helloDecodeJSON configures JSON decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.
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)
// gopherDecodeYAML configures YAML decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.
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)
// gopherAs executes the command and decodes its selected output into T.
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)
// CoffeeInto executes the command and decodes into dst.
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)
// gopherDecode configures a custom decoder for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.
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)
// gopherDecodeWith executes the command and decodes stdout into dst.
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)
// gopherDecode implements Decoder.
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)
// CoffeeFromCombined decodes from combined stdout+stderr.
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)
// gopherFromStderr decodes from stderr.
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)
// gopherFromStdout decodes from stdout (default).
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)
// gopherTrim trims whitespace before decoding.
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)
// gopherPipe 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.
out, err := process.Command("printf", "go").
Pipe("tr", "a-z", "A-Z").
OutputTrimmed()
if err != nil {
return err
}
fmt.Println(out)
// GOPipelineResults executes the command and returns per-stage results and the first execution error. Non-zero exit codes remain data in their corresponding Result. With CheckExit, the returned error follows the selected pipeline exit policy while the individual stage results remain unchanged.
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)
// go GOPipeBestEffort selects the last stage as the primary result while surfacing the first execution error. Every stage is started concurrently.
res, err := process.Command("false").
Pipe("printf", "ok").
PipeBestEffort().
Run()
if err != nil {
return err
}
fmt.Print(res.Stdout)
// okPipeStrict selects the first stage with an execution error or non-zero exit as the primary result. Every stage is still started concurrently.
res, err := process.Command("false").
Pipe("printf", "ok").
PipeStrict().
Run()
if err != nil {
return err
}
fmt.Println(res.ExitCode != 0)
// trueWithProcessTree returns a runner that includes descendants in cancellation and termination. Settings are local to the returned value; no global configuration is changed.
result, err := process.WithProcessTree().Run(context.Background(), "go", "version")
if err != nil {
return err
}
fmt.Println(result.OK())
// trueWithProcessTree 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.
result, err := process.Command("go", "version").WithProcessTree().Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// trueCreationFlags is a no-op on non-Windows platforms; on Windows it sets process creation flags.
result, err := process.Command("go", "version").CreationFlags(process.CreateNewProcessGroup).Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// trueHideWindow is a no-op on non-Windows platforms; on Windows it hides console windows.
result, err := process.Command("go", "version").HideWindow(true).Run()
if err != nil {
return err
}
fmt.Println(result.OK())
// truePdeathsig signals the child when its creating OS thread exits on Linux. It is a no-op on other platforms.
out, err := process.Command("printf", "ok").Pdeathsig(syscall.SIGTERM).Output()
if err != nil {
return err
}
fmt.Print(out)
// okSetpgid places the child in a new process group for group signals.
out, err := process.Command("printf", "ok").Setpgid(true).Output()
if err != nil {
return err
}
fmt.Print(out)
// okSetsid starts the child in a new session, detaching it from the terminal.
out, err := process.Command("printf", "ok").Setsid(true).Output()
if err != nil {
return err
}
fmt.Print(out)
// okShadowPrint configures shadow printing for this command chain.
result, err := process.Command("printf", "hello").ShadowPrint().Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// helloWithMask applies a masker to the shadow-printed command string.
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())
// trueShadowOff disables shadow printing for this command chain, preserving configuration.
result, err := process.Command("printf", "hello").ShadowPrint().ShadowOff().Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// helloShadowOn enables shadow printing using the previously configured options.
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)
// helloWithFormatter sets a formatter for ShadowPrint output.
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)
// helloWithPrefix sets the shadow print prefix.
result, err := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build")).Run()
if err != nil {
return err
}
fmt.Println(result.Stdout)
// helloArg appends arguments to the command.
cmd := process.Command("printf").Arg("hello")
out, err := cmd.Output()
if err != nil {
return err
}
fmt.Print(out)
// helloArgs returns the argv slice used for execution.
cmd := process.Command("go", "env", "GOOS")
fmt.Println(strings.Join(cmd.Args(), " "))
// go env GOOSShellEscaped returns a shell-escaped string for logging only.
cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.ShellEscaped())
// echo 'hello world' "it's"String returns a human-readable representation of the command.
cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.String())
// echo "hello world" it'sError returns the wrapped error message when available.
err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Error())
// boomError reports the exit status without including potentially sensitive output.
err := process.ExitError{Result: process.Result{ExitCode: 7}}
fmt.Println(err.Error())
// process: command exited with status 7Error distinguishes inactivity from an elapsed total deadline.
err := process.TimeoutError{Idle: true}
fmt.Println(err.Error())
// process: idle timeout exceededUnwrap preserves deadline classification and any execution failures collected before cancellation.
err := process.TimeoutError{}
fmt.Println(errors.Is(err.Unwrap(), context.DeadlineExceeded))
// trueUnwrap exposes the underlying error.
err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Unwrap() != nil)
// trueDir sets the working directory.
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)
// truemake 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.
