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.
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.
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.
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
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
$VARSdo not work unless you runsh -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. ACmdcan be run only once; build a new one for each execution.- Always
WaitafterStart, or the process becomes a zombie and pipe resources leak. WithStdoutPipe, finish reading before callingWait. Outputcaptures only stdout. IfStderris nil, it fillsExitError.Stderrwith the tail of stderr for error messages.- Setting
Envreplaces everything, includingPATH. Append toos.Environ()to add a variable:cmd.Env = append(os.Environ(), "DEBUG=1"). CommandContextkills only the process it started, not its children. UseCanceland process groups (SysProcAttr) when the program spawns sub-processes.- Windows: the program name must usually include
.exeor be found viaPATHEXT; shell built-ins likedirneedcmd /c. - Since Go 1.19 a relative
PATHhit in the current directory is rejected withErrDot, closing a classic security hole. - Exit status vs error: a program that ran and returned 1 gives an
ExitError; checkExitCode()rather than parsing the message. A process killed by a signal reports-1. - Use
os/signalandcmd.Process.Signalto forward interrupts to child processes in long-running tools.
Related
ospackage,io.Readerandio.Writer,bufio.Scanner,context,os/signal- Lessons: os/exec, Context