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

tgo*_*gos 0 pipe exec go

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

out, err := exec.Command("ps", "cax").Output()
Run Code Online (Sandbox Code Playgroud)

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

out, err := exec.Command("ps", "cax | grep myapp").Output()
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Nad*_*adh 12

将所有内容传递给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))
}
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 6

你可以这样做:

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

  • 当您使用“bash -c”时,您不会收到有关内部命令错误的通知。@Nadh 建议的方法的优点是,如果内部命令“ps cax”失败并返回非零值,则会返回错误。 (2认同)