Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

pipe

go

exec

The following works and prints the command output:

out, err := exec.Command("ps", "cax").Output()

but this one fails (with exit status 1):

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

Any suggestions?

like image 227
tgogos Avatar asked Dec 08 '16 11:12

tgogos


3 Answers

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))
}
like image 97
Nadh Avatar answered Nov 05 '22 00:11

Nadh


You could do:

out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output()
like image 30
Ashwini Chaudhary Avatar answered Nov 04 '22 22:11

Ashwini Chaudhary


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())
      }
   }
}
like image 2
Zombo Avatar answered Nov 04 '22 23:11

Zombo