go使用exec.Command执行带管道的命令

分类: go

2019-09-12

|

3038

|

评论:3

分享:

在go中我们想执行带管道的命令时(如:ps aux|grep go),不能直接像下面这样:

exec.Command("ps", "aux", "|", "grep", "go")

这样做不会有任何输出。

有两种方法可以做到:

  1. 使用 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)
    
  2. 使用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()获取输出



转载请注明来源

文章:go使用exec.Command执行带管道的命令

链接:/article/44

作者:gojuukaze

本文共 3 个回复

?
发布于:2019年11月1日 19:28

你好!

我想执行 这条命令

<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-weight: normal;font-size: 14px;line-height: 19px;white-space: pre;"><div>iptables -L -v -n -x | grep :80123 | awk '{print $2}'</div></div>


<div style="color: #d4d4d4;background-color: #1e1e1e;font-family: Consolas, 'Courier New', monospace;font-weight: normal;font-size: 14px;line-height: 19px;white-space: pre;"><div>c := cmd.NewCmd("iptables""-L" , "-v" , "-n" , "-x" , "| grep :10081 | awk '{print $2}'")</div></div>


我这样写 是错误的 我该怎样写? 求解 非常感谢


gojuukaze
发布于:2020年1月15日 12:18

回复 ? : 文章里已经写了啊:

cmd.NewCmd("bash", "-c", "iptables -L -v -n -x | grep :80123 | awk '{print $2}'")

Yexiaomo
发布于:2021年7月28日 17:16
您好, go的管道命令为什么加上 bash -c 就可以了? 希望能收到回复,谢谢!

gojuukaze
发布于:2021年7月30日 11:24

回复 Yexiaomo

管道是shell下的一个特性,但go的command并没有启动一个shell,而是直接运行对应的程序,所以管道无效。

 bash -c ,  其实是启动了bash这个shell程序;-c 是他的参数,表示执行后面的命令

Yexiaomo
发布于:2021年8月5日 15:01

回复 gojuukaze : 貌似有点懂了, 非常感谢, 我再仔细看看!



发表评论 (对文章评论)

captcha