How to Pipe Several Commands in Go

Created
Modified

Using piped commands

For example, this function retrieves the CPU model name using piped commands:

package main

import (
  "fmt"
  "os/exec"
)

func main() {
  cmd := "cat /proc/cpuinfo | egrep '^model name' | uniq | awk '{print substr($0, index($0,$4))}'"
  o, err := exec.Command("bash", "-c", cmd).Output()
  if err != nil {
    // log.Fatal
  }
  fmt.Println(string(o))
}
Intel(R) Core(TM) i5 CPU M 460 @ 2.53GHz

Using StdoutPipe

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts. The pipe will be closed automatically after Wait sees the command exit.

package main

import (
  "bytes"
  "fmt"
  "io"
  "os"
  "os/exec"
)

func main() {
  c1 := exec.Command("ls")
  c2 := exec.Command("wc", "-l")

  r, w := io.Pipe()
  c1.Stdout = w
  c2.Stdin = r

  var b2 bytes.Buffer
  c2.Stdout = &b2

  c1.Start()
  c2.Start()
  c1.Wait()
  w.Close()
  c2.Wait()
  io.Copy(os.Stdout, &b2)

  fmt.Println(b2.String())
}
6

Related Tags