Go exec.Command() - run command which contains pipe

Passing everything to bash works, but here's a more idiomatic way of doing it.

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    grep := exec.Command("grep", "redis")
    ps := exec.Command("ps", "cax")

    // Get ps's stdout and attach it to grep's stdin.
    pipe, _ := ps.StdoutPipe()
    defer pipe.Close()

    grep.Stdin = pipe

    // Run ps first.
    ps.Start()

    // Run and get the output of grep.
    res, _ := grep.Output()

    fmt.Println(string(res))
}

You could do:

out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output()

In this specific case, you don't really need a pipe, a Go can grep as well:

package main

import (
   "bufio"
   "bytes"
   "os/exec"
   "strings"
)

func main() {
   c, b := exec.Command("go", "env"), new(bytes.Buffer)
   c.Stdout = b
   c.Run()
   s := bufio.NewScanner(b)
   for s.Scan() {
      if strings.Contains(s.Text(), "CACHE") {
         println(s.Text())
      }
   }
}