How to Execute a Shell Command in Go


Using exec.Command Function

Command returns the Cmd struct to execute the named program with the given arguments.

You can execute a shell command using the exec.Command() function. For example,

package main

import (

func main() {
  cmd := exec.Command("ls", "-lh")

  var out bytes.Buffer
  cmd.Stdout = &out
  err := cmd.Run()
  if err != nil {
    // log.Fatal(err)
total 188K

Related Tags