os/exec
Run executables directly, capture output, and configure the working directory and environment.
Run a command#
Command(name string, args ...string) Cmd constructs a command. Arguments are passed directly to the executable; a shell is used only when you explicitly run one. Run() Result<int> inherits standard streams and returns zero on success. Output() Result<string> captures stdout and inherits stderr. CombinedOutput() Result<string> captures stdout and stderr together in their write order.
package main;
import "os/exec";
import "io";
func main() {
command := exec.Command("printf", "%s", "hello world");
output := command.Output().unwrap();
io.Println(output).unwrap();
command = exec.Command("/bin/sh", "-c", "printf '%s' \"$GREETING\"");
command.Dir = "/tmp";
command.Env = string[]{"GREETING=hello"};
io.Println(command.CombinedOutput().unwrap()).unwrap();
}
Configure and find executables#
Cmd has Path, Args, Dir, Env, and ExitCode fields. Args excludes argv[0]. Empty Dir inherits the current working directory. Empty Env inherits the parent environment; a nonempty Env replaces it with KEY=value strings. Empty Env cannot request an empty child environment.
LookPath(name string) Result<string> checks an explicit executable path or searches PATH. Implicit relative PATH results are errors; use an explicit path to run from the current directory.
Command execution uses posix_spawnp directly; it does not call LookPath. To require the relative-PATH rejection described above, resolve the name with LookPath and pass its successful result to Command. PATH lookup uses the parent process environment, so setting Cmd.Env does not choose the executable search path.
Exit errors and lifecycle#
Execute each Cmd once. Missing executables, NUL-containing arguments/paths/environment entries, spawn or wait failures, and nonzero or signal exits return errors. ExitCode is -1 before completion or on a signal, otherwise the child exit code. Output methods return errors on nonzero exits and do not return partial output alongside the error.
Output capture uses temporary files, avoiding pipe-buffer deadlocks. Files and spawn actions are cleaned up, and interrupted waits are retried. Captured strings can contain embedded NUL bytes. Output capture has no size bound. Start/Wait, pipes, configurable streams, timeout, cancellation, and Windows/macOS backends are not implemented.
Run process tests#
Tests cover argument boundaries, literal shell characters, output capture, combined streams, large output, environment and working-directory configuration, executable lookup, command reuse, and failure status.
OCEAN_SRC=/path/to/ocean-src ocean test /path/to/ocean-src/os/exec