去exec.Command() - 运行包含管道的命令

时间:2016-12-08 11:02:38

标签: go pipe exec

以下工作并打印命令输出:

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

但是这个失败了(退出状态为1):

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

有什么建议吗?

3 个答案:

答案 0 :(得分:8)

将所有内容传递给bash都有效,但这是一种更惯用的方式。

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

答案 1 :(得分:6)

你可以这样做:

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

答案 2 :(得分:0)

在这种特定情况下,您实际上并不需要管道,Go 也可以grep

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