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

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

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

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

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

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

有什么建议吗?

你可以这样做:

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

将所有内容传递给 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))
}

在这种特定情况下,您实际上并不需要管道,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())
      }
   }
}