Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Errors, I/O and Files

Go os/exec package

Reference for Go os/exec: exec.Command, Run, Output, CombinedOutput, Start/Wait, pipes, stdin, environment, CommandContext timeouts and ExitError.

The os/exec package starts external programs. exec.Command builds a *exec.Cmd describing the program, its arguments, environment, working directory and standard streams; methods such as Run, Output and CombinedOutput then execute it and wait for it to finish.

Go does not run commands through a shell. exec.Command("ls", "-l", dir) passes each argument exactly as given, so spaces, quotes and ; in an argument are harmless. That makes it much safer than building a shell string, as long as you do not deliberately start sh -c with untrusted text.

Go
out, err := exec.Command("git", "rev-parse", "HEAD").Output()

Try it

The runner sandbox has no network and a minimal system, but echo, cat, sleep and sh exist, so the examples use only those.

Go Output, errors and exit codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Stdin, pipes, environment and timeouts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Command(name string, arg ...string) *Cmd
func CommandContext(ctx context.Context, name string, arg ...string) *Cmd
func LookPath(file string) (string, error)

func (c *Cmd) Run() error
func (c *Cmd) Output() ([]byte, error)
func (c *Cmd) CombinedOutput() ([]byte, error)
func (c *Cmd) Start() error
func (c *Cmd) Wait() error
func (c *Cmd) StdinPipe() (io.WriteCloser, error)
func (c *Cmd) StdoutPipe() (io.ReadCloser, error)
func (c *Cmd) StderrPipe() (io.ReadCloser, error)
Cmd field Description
Path, Args Resolved program and full argument vector (Args[0] is the program name).
Env KEY=value list. nil means "inherit the parent's environment".
Dir Working directory; empty means the current one.
Stdin, Stdout, Stderr io.Reader / io.Writer values. nil means the null device; os.Stdout attaches the terminal.
Cancel, WaitDelay Custom cancellation action and a grace period for slow-closing pipes (Go 1.20).
ProcessState After Wait: exit code, timing, success flag.

Errors: *exec.ExitError for a non-zero exit (ExitCode(), and Stderr when you used Output); exec.ErrNotFound when the program is not on PATH; *exec.Error for other start failures; exec.ErrDot when the match would come from the current directory.

Usage notes

  • No shell: wildcards, pipes, redirections and $VARS do not work unless you run sh -c "..." yourself. When you do, never splice untrusted input into the script string; pass it as separate arguments (sh -c 'cat "$1"' sh file).
  • Run = Start + Wait. A Cmd can be run only once; build a new one for each execution.
  • Always Wait after Start, or the process becomes a zombie and pipe resources leak. With StdoutPipe, finish reading before calling Wait.
  • Output captures only stdout. If Stderr is nil, it fills ExitError.Stderr with the tail of stderr for error messages.
  • Setting Env replaces everything, including PATH. Append to os.Environ() to add a variable: cmd.Env = append(os.Environ(), "DEBUG=1").
  • CommandContext kills only the process it started, not its children. Use Cancel and process groups (SysProcAttr) when the program spawns sub-processes.
  • Windows: the program name must usually include .exe or be found via PATHEXT; shell built-ins like dir need cmd /c.
  • Since Go 1.19 a relative PATH hit in the current directory is rejected with ErrDot, closing a classic security hole.
  • Exit status vs error: a program that ran and returned 1 gives an ExitError; check ExitCode() rather than parsing the message. A process killed by a signal reports -1.
  • Use os/signal and cmd.Process.Signal to forward interrupts to child processes in long-running tools.