LESSON · 1 OF 23

Building a command with exec.Command

Building a command with exec.Command

DevOps code shells out constantly - calling kubectl, git, terraform, or a plain ls. Go does this through the os/exec package, and it starts with exec.Command.

exec.Command builds a command but does not run it yet. The first argument is the program name; every argument after it is a separate string:

go
import "os/exec"

cmd := exec.Command("ls", "-l", "/tmp")

Each piece is its own string. You do NOT write exec.Command("ls -l /tmp") as one string. There is no shell here to split that on spaces, so Go would look for a program literally named ls -l /tmp and fail to find it.

The rule to memorise: program name first, then one string per argument. What you get back is a *exec.Cmd value that you run in a later step.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute