如何在切片中连接多个管道命令

时间:2014-06-19 08:05:09

标签: go

我已经检查了这个link关于如何连接两个管道命令,如下面的代码。

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

但是现在我有几个命令超过2.命令将以c1 | c2 | c3 | c4 | c5运行,并且这些命令放在一个切片([](*exec.Cmd))中。

问题
如何循环切片并执行命令作为序列并获得最终结果?谢谢。

1 个答案:

答案 0 :(得分:2)

你必须做你目前正在做的事情,除了你必须用循环做。这是一个完整的例子,它只是你自己的例子:

package main

import (
    "os"
    "os/exec"
)

func main() {
    var err error // To store error during the processing. You should always check for errors and handle them. That's not an option.
    var commands []*exec.Cmd // The slice that will store the commands.

    // You own commands
    commands = append(commands, exec.Command("ls"))
    commands = append(commands, exec.Command("wc", "-l"))

    // Connect each command input to the output of the previous command (starting with the second command, obviously)
    for i := 1; i < len(commands); i++ {
        commands[i].Stdin, err = commands[i - 1].StdoutPipe()
        if err != nil {
            panic(err)
        }
    }
    commands[len(commands)-1].Stdout = os.Stdout // Last command output is connected to the standard output

    // Start each command. note that the reverse order isn't mandatory, you just have to avoid runing the first command now
    for i := len(commands) - 1; i > 0; i-- {
        err = commands[i].Start()
        if err != nil {
            panic(err)
        }
    }

    // Run the first command
    commands[0].Run()
    // Then wait for each subsequent command to finish
    for i := 1; i < len(commands); i++ {
        err = commands[i].Wait()
        if err != nil {
            panic(err)
        }
    }
}