Namespace: go.std.os.exec
v1.0Contents
Summary
Provides a low-level interface to the os/exec package.
Package exec runs external commands. It wraps os.StartProcess to make it
easier to remap stdin and stdout, connect I/O with pipes, and do other
adjustments.
Unlike the "system" library call from C and other languages, the
os/exec package intentionally does not invoke the system shell and
does not expand any glob patterns or handle other expansions,
pipelines, or redirections typically done by shells. The package
behaves more like C's "exec" family of functions. To expand glob
patterns, either call the shell directly, taking care to escape any
dangerous input, or use the path/filepath package's Glob function.
To expand environment variables, use package os's ExpandEnv.
Note that the examples in this package assume a Unix system.
They may not run on Windows, and they do not run in the Go Playground
used by golang.org and godoc.org.
# Executables in the current directory
The functions Command and LookPath look for a program
in the directories listed in the current path, following the
conventions of the host operating system.
Operating systems have for decades included the current
directory in this search, sometimes implicitly and sometimes
configured explicitly that way by default.
Modern practice is that including the current directory
is usually unexpected and often leads to security problems.
To avoid those security problems, as of Go 1.19, this package will not resolve a program
using an implicit or explicit path entry relative to the current directory.
That is, if you run exec.LookPath("go"), it will not successfully return
./go on Unix nor .\go.exe on Windows, no matter how the path is configured.
Instead, if the usual path algorithms would result in that answer,
these functions return an error err satisfying errors.Is(err, ErrDot).
For example, consider these two program snippets:
path, err := exec.LookPath("prog")
if err != nil {
log.Fatal(err)
}
use(path)
and
cmd := exec.Command("prog")
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
These will not find and run ./prog or .\prog.exe,
no matter how the current path is configured.
Code that always wants to run a program from the current directory
can be rewritten to say "./prog" instead of "prog".
Code that insists on including results from relative path entries
can instead override the error using an errors.Is check:
path, err := exec.LookPath("prog")
if errors.Is(err, exec.ErrDot) {
err = nil
}
if err != nil {
log.Fatal(err)
}
use(path)
and
cmd := exec.Command("prog")
if errors.Is(cmd.Err, exec.ErrDot) {
cmd.Err = nil
}
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
Setting the environment variable GODEBUG=execerrdot=0
disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19
behavior for programs that are unable to apply more targeted fixes.
A future version of Go may remove support for this variable.
Before adding such overrides, make sure you understand the
security implications of doing so.
See https://go.dev/blog/path-security for more information.
Index
- *Cmd
- *Error
- *ExitError
- Cmd
- Command
- CommandContext
- ErrDot
- ErrNotFound
- Error
- ExitError
- LookPath
- arrayOfCmd
- arrayOfError
- arrayOfExitError
Legend
-
Constant
Variable
Function
Macro
Special form
Type
GoVar
Receiver/Method
Constants
Constants are variables with :const true in their metadata. Joker currently does not recognize them as special; as such, it allows redefining them or their values.-
(None.)
Variables
-
ErrDot
Var v1.0ErrDot indicates that a path lookup resolved to an executable
in the current directory due to ‘.’ being in the path, either
implicitly or explicitly. See the package documentation for details.
Note that functions in this package do not return ErrDot directly.
Code should use errors.Is(err, ErrDot), not err == ErrDot,
to test whether a returned error err is due to this condition.
-
ErrNotFound
Var v1.0ErrNotFound is the error resulting if a path search failed to find an executable file.
Functions, Macros, and Special Forms
-
Command
Function v1.0(Command name & arg)
Command returns the Cmd struct to execute the named program with
the given arguments.
It sets only the Path and Args in the returned structure.
If name contains no path separators, Command uses LookPath to
resolve name to a complete path if possible. Otherwise it uses name
directly as Path.
The returned Cmd's Args field is constructed from the command name
followed by the elements of arg, so arg should not include the
command name itself. For example, Command("echo", "hello").
Args[0] is always name, not the possibly resolved Path.
On Windows, processes receive the whole command line as a single string
and do their own parsing. Command combines and quotes Args into a command
line string with an algorithm compatible with applications using
CommandLineToArgvW (which is the most common way). Notable exceptions are
msiexec.exe and cmd.exe (and thus, all batch files), which have a different
unquoting algorithm. In these or other similar cases, you can do the
quoting yourself and provide the full command line in SysProcAttr.CmdLine,
leaving Args empty.
Go input arguments: (name string, arg ...string)
Go returns: *Cmd
Joker input arguments: [^String name, & ^String arg]
Joker returns: ^*Cmd -
CommandContext
Function v1.0(CommandContext ctx name & arg)
CommandContext is like Command but includes a context.
The provided context is used to kill the process (by calling
os.Process.Kill) if the context becomes done before the command
completes on its own.
Go input arguments: (ctx context.Context, name string, arg ...string)
Go returns: *Cmd
Joker input arguments: [^go.std.context/Context ctx, ^String name, & ^String arg]
Joker returns: ^*Cmd -
LookPath
Function v1.0(LookPath file)
LookPath searches for an executable named file in the
directories named by the PATH environment variable.
LookPath also uses PATHEXT environment variable to match
a suitable candidate.
If file contains a slash, it is tried directly and the PATH is not consulted.
Otherwise, on success, the result is an absolute path.
In older versions of Go, LookPath could return a path relative to the current directory.
As of Go 1.19, LookPath will instead return that path along with an error satisfying
errors.Is(err, ErrDot). See the package documentation for more details.
Go input arguments: (file string)
Go returns: (string, error)
Joker input arguments: [^String file]
Joker returns: [^String, ^Error]
Types
-
*Cmd
Concrete Type v1.0Cmd represents an external command being prepared or run.
A Cmd cannot be reused after calling its Run, Output or CombinedOutput
methods.
-
CombinedOutput
Receiver for *Cmd v1.0([])
CombinedOutput runs the command and returns its combined standard
output and standard error.
-
Environ
Receiver for *Cmd v1.0([])
Environ returns a copy of the environment in which the command would be run
as it is currently configured.
-
Output
Receiver for *Cmd v1.0([])
Output runs the command and returns its standard output.
Any returned error will usually be of type *ExitError.
If c.Stderr was nil, Output populates ExitError.Stderr.
-
Run
Receiver for *Cmd v1.0([])
Run starts the specified command and waits for it to complete.
The returned error is nil if the command runs, has no problems
copying stdin, stdout, and stderr, and exits with a zero exit
status.
If the command starts but does not complete successfully, the error is of
type *ExitError. Other error types may be returned for other situations.
If the calling goroutine has locked the operating system thread
with runtime.LockOSThread and modified any inheritable OS-level
thread state (for example, Linux or Plan 9 name spaces), the new
process will inherit the caller's thread state.
-
Start
Receiver for *Cmd v1.0([])
Start starts the specified command but does not wait for it to complete.
If Start returns successfully, the c.Process field will be set.
After a successful call to Start the Wait method must be called in
order to release associated system resources.
-
StderrPipe
Receiver for *Cmd v1.0([])
StderrPipe returns a pipe that will be connected to the command's
standard error when the command starts.
Wait will close the pipe after seeing the command exit, so most callers
need not close the pipe themselves. It is thus incorrect to call Wait
before all reads from the pipe have completed.
For the same reason, it is incorrect to use Run when using StderrPipe.
See the StdoutPipe example for idiomatic usage.
-
StdinPipe
Receiver for *Cmd v1.0([])
StdinPipe returns a pipe that will be connected to the command's
standard input when the command starts.
The pipe will be closed automatically after Wait sees the command exit.
A caller need only call Close to force the pipe to close sooner.
For example, if the command being run will not exit until standard input
is closed, the caller must close the pipe.
-
StdoutPipe
Receiver for *Cmd v1.0([])
StdoutPipe returns a pipe that will be connected to the command's
standard output when the command starts.
Wait will close the pipe after seeing the command exit, so most callers
need not close the pipe themselves. It is thus incorrect to call Wait
before all reads from the pipe have completed.
For the same reason, it is incorrect to call Run when using StdoutPipe.
See the example for idiomatic usage.
-
String
Receiver for *Cmd v1.0([])
String returns a human-readable description of c.
It is intended only for debugging.
In particular, it is not suitable for use as input to a shell.
The output of String may vary across Go releases.
-
Wait
Receiver for *Cmd v1.0([])
Wait waits for the command to exit and waits for any copying to
stdin or copying from stdout or stderr to complete.
The command must have been started by Start.
The returned error is nil if the command runs, has no problems
copying stdin, stdout, and stderr, and exits with a zero exit
status.
If the command fails to run or doesn't complete successfully, the
error is of type *ExitError. Other error types may be
returned for I/O problems.
If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits
for the respective I/O loop copying to or from the process to complete.
Wait releases any resources associated with the Cmd.
-
*Error
Concrete Type v1.0Error is returned by LookPath when it fails to classify a file as an
executable.
-
Error
Receiver for *Error v1.0([])
-
Unwrap
Receiver for *Error v1.0([])
-
*ExitError
Concrete Type v1.0An ExitError reports an unsuccessful exit by a command.
-
Error
Receiver for *ExitError v1.0([])
-
ExitCode
Receiver for *ExitError v1.0([])
ExitCode returns the exit code of the exited process, or -1
if the process hasn't exited or was terminated by a signal.
-
Exited
Receiver for *ExitError v1.0([])
Exited reports whether the program has exited.
On Unix systems this reports true if the program exited due to calling exit,
but false if the program terminated due to a signal.
-
Pid
Receiver for *ExitError v1.0([])
Pid returns the process id of the exited process.
-
String
Receiver for *ExitError v1.0([])
-
Success
Receiver for *ExitError v1.0([])
Success reports whether the program exited successfully,
such as with exit status 0 on Unix.
-
Sys
Receiver for *ExitError v1.0([])
Sys returns system-dependent exit information about
the process. Convert it to the appropriate underlying
type, such as syscall.WaitStatus on Unix, to access its contents.
-
SysUsage
Receiver for *ExitError v1.0([])
SysUsage returns system-dependent resource usage information about
the exited process. Convert it to the appropriate underlying
type, such as *syscall.Rusage on Unix, to access its contents.
(On Unix, *syscall.Rusage matches struct rusage as defined in the
getrusage(2) manual page.)
-
SystemTime
Receiver for *ExitError v1.0([])
SystemTime returns the system CPU time of the exited process and its children.
-
UserTime
Receiver for *ExitError v1.0([])
UserTime returns the user CPU time of the exited process and its children.
-
Cmd
Concrete Type v1.0Cmd represents an external command being prepared or run.
A Cmd cannot be reused after calling its Run, Output or CombinedOutput
methods.
-
Error
Concrete Type v1.0Error is returned by LookPath when it fails to classify a file as an
executable.
-
ExitError
Concrete Type v1.0An ExitError reports an unsuccessful exit by a command.
-
ExitCode
Receiver for ExitError v1.0([])
ExitCode returns the exit code of the exited process, or -1
if the process hasn't exited or was terminated by a signal.
-
Exited
Receiver for ExitError v1.0([])
Exited reports whether the program has exited.
On Unix systems this reports true if the program exited due to calling exit,
but false if the program terminated due to a signal.
-
Pid
Receiver for ExitError v1.0([])
Pid returns the process id of the exited process.
-
String
Receiver for ExitError v1.0([])
-
Success
Receiver for ExitError v1.0([])
Success reports whether the program exited successfully,
such as with exit status 0 on Unix.
-
Sys
Receiver for ExitError v1.0([])
Sys returns system-dependent exit information about
the process. Convert it to the appropriate underlying
type, such as syscall.WaitStatus on Unix, to access its contents.
-
SysUsage
Receiver for ExitError v1.0([])
SysUsage returns system-dependent resource usage information about
the exited process. Convert it to the appropriate underlying
type, such as *syscall.Rusage on Unix, to access its contents.
(On Unix, *syscall.Rusage matches struct rusage as defined in the
getrusage(2) manual page.)
-
SystemTime
Receiver for ExitError v1.0([])
SystemTime returns the system CPU time of the exited process and its children.
-
UserTime
Receiver for ExitError v1.0([])
UserTime returns the user CPU time of the exited process and its children.
-
arrayOfCmd
Concrete Type v1.0Cmd represents an external command being prepared or run.
A Cmd cannot be reused after calling its Run, Output or CombinedOutput
methods.
-
arrayOfError
Concrete Type v1.0Error is returned by LookPath when it fails to classify a file as an
executable.
-
arrayOfExitError
Concrete Type v1.0An ExitError reports an unsuccessful exit by a command.