Go - 使用os.exec()管道3个或更多命令?

时间:2016-12-28 12:13:25

标签: go

如何在Go中管理3+个命令(例如ls | grep | wc)?我试图修改这个用于管道2命令的代码,但无法弄清楚正确的方法。,

package main

import (
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    c2 := exec.Command("wc", "-l")
    c2.Stdin, _ = c1.StdoutPipe()
    c2.Stdout = os.Stdout
    _ = c2.Start()
    _ = c1.Run()
    _ = c2.Wait()
}

https://stackoverflow.com/a/10953142/3761308

1 个答案:

答案 0 :(得分:1)

package main

import (
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    c2 := exec.Command("grep", "-i", "o")
    c3 := exec.Command("wc", "-l")
    c2.Stdin, _ = c1.StdoutPipe()
    c3.Stdin, _ = c2.StdoutPipe()
    c3.Stdout = os.Stdout
    _ = c3.Start()
    _ = c2.Start()
    _ = c1.Run()
    _ = c2.Wait()
    _ = c3.Wait()
}