Executing commands

The os/exec package has functions to run externalcommands, and is the premier way to execute commands from within a Go program.It works by defining a *exec.Cmd structure for which it defines a number ofmethods. Let’s execute ls -l:

  1. import "os/exec"
  2. cmd := exec.Command("/bin/ls", "-l")
  3. err := cmd.Run()

The above example just runs “ls -l” without doing anything with the returneddata, capturing the standard output from a command is done as follows:

  1. cmd := exec.Command("/bin/ls", "-l")
  2. buf, err := cmd.Output()

And buf is byte slice, that you can further use in your program.