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))
}

Leave a Comment