Running commands with os/exec
- Version
- 1.27
- Review
- Draft
Summary#
os/exec starts a program with a list of arguments and does not invoke a shell. Output runs it and returns standard output. An unsuccessful exit yields an *exec.ExitError. Failures to start the program can return other errors.
Syntax#
command := exec.Command(name, args...)
output, err := command.Output()
// For a command tied to a context:
command = exec.CommandContext(ctx, name, args...)
Example#
The program starts a second copy of itself as the child, so it depends on no external tool.
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
)
const childKey = "DEVLOOKUP_EXAMPLE_CHILD"
func child(mode string) {
if mode == "fail" {
fmt.Fprintln(os.Stderr, "disk is full")
os.Exit(3)
}
input, err := io.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Printf("args=%q input=%q\n", os.Args[1:], input)
}
func start(ctx context.Context, mode string, args ...string) ([]byte, error) {
self, err := os.Executable()
if err != nil {
return nil, err
}
command := exec.CommandContext(ctx, self, args...)
command.Env = append(os.Environ(), childKey+"="+mode)
command.Stdin = strings.NewReader("hello")
return command.Output()
}
func main() {
if mode := os.Getenv(childKey); mode != "" {
child(mode)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
output, err := start(ctx, "echo", "two words", "$HOME", "*.go")
fmt.Print(string(output))
fmt.Println("error:", err)
_, err = start(ctx, "fail")
var exitError *exec.ExitError
if errors.As(err, &exitError) {
fmt.Println("exit code:", exitError.ExitCode())
fmt.Printf("stderr: %q\n", exitError.Stderr)
}
}
Expected output#
args=["two words" "$HOME" "*.go"] input="hello"
error: <nil>
exit code: 3
stderr: "disk is full\n"
Common mistakes#
Pass each argument separately; a whole command line in the name is treated as one program name. Globs, $VARIABLES, pipes and redirects are not expanded. Building a sh -c string from untrusted input allows shell injection.
Version applicability#
Command and Output work from Go 1.0. CommandContext arrived in Go 1.7 and kills the started process by default on cancellation. The example also uses os.Executable (Go 1.8), ExitCode (Go 1.12), errors.As (Go 1.13) and io.ReadAll (Go 1.16), so it requires Go 1.16 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0