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

不羁岁月 提交于 2019-12-24 11:37:12

问题


The following works and prints the command output:

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

but this one fails (with exit status 1):

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

Any suggestions?


回答1:


You could do:

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



回答2:


Passing everything to bash works, but here's a more idiomatic way of doing it.

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


来源:https://stackoverflow.com/questions/41037870/go-exec-command-run-command-which-contains-pipe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!