原文链接 : https://www.ikaze.cn/article/44
在go中我们想执行带管道的命令时(如:ps aux|grep go
),不能直接像下面这样:
exec.Command("ps", "aux", "|", "grep", "go")
这样做不会有任何输出。
有两种方法可以做到:
使用
sh -c ""
命令exec.Command("bash", "-c", "ps aux|grep go")
这是推荐的做法。
如果输出不是很多,推荐使用github.com/go-cmd/cmd
库来执行系统命令,如:import "github.com/go-cmd/cmd" c := cmd.NewCmd("bash", "-c", "ps aux|grep go") <-c.Start() fmt.Println(c.Status().Stdout)
使用
io.Pipe()
连接两个命令ps := exec.Command("ps", "aux") grep := exec.Command("grep", "go") r, w := io.Pipe() // 创建一个管道 defer r.Close() defer w.Close() ps.Stdout = w // ps向管道的一端写 grep.Stdin = r // grep从管道的一端读 var buffer bytes.Buffer grep.Stdout = &buffer ps.Start() grep.Start() ps.Wait() w.Close() grep.Wait() io.Copy(os.Stdout, &buffer)
第二种方法非常不方便,而且无法使用
grep.Stdout()
,grep.StdoutPipe()
获取输出
有疑问加站长微信联系(非本文作者)

如何只抛出执行命令,不等待返回结果呢?
异步啊。等什么
cmd 有个start方法不用等待 https://pkg.go.dev/os/exec#Cmd.Start
thanks a lot by XJD