Skip to content

Instantly share code, notes, and snippets.

@alihammad-gist
Created April 16, 2016 16:09
Show Gist options
  • Save alihammad-gist/0e7486cd114e3467ee0d88ee4d7a0669 to your computer and use it in GitHub Desktop.
Save alihammad-gist/0e7486cd114e3467ee0d88ee4d7a0669 to your computer and use it in GitHub Desktop.
cmd pipe
package main
import (
"errors"
"io"
"os/exec"
)
var (
// ErrNoCommandsProvided is returned when there were no commands provided to
// pipe method.
ErrNoCommandsProvided = errors.New("No commands were provided")
)
// Pipe provides the ability to pipe multiples commands stdin and stdout
// together. in and out represent both ends of the pipe.
// in will be hooked to first commands
func Pipe(in io.Reader, out io.Writer, errWriter io.Writer, cmds ...*exec.Cmd) error {
if len(cmds) == 0 {
return ErrNoCommandsProvided
}
// setting stdin and out
cmds[0].Stdin = in
cmds[len(cmds)-1].Stdout = out
for i, _ := range cmds {
if cmds[i].Stdin == nil {
pout, err := cmds[i-1].StdoutPipe()
if err != nil {
return err
}
cmds[i].Stdin = pout
}
cmds[i].Stderr = errWriter
}
// starting
for i, _ := range cmds {
if err := cmds[i].Start(); err != nil {
return err
}
}
// waiting
for i, _ := range cmds {
if err := cmds[i].Wait(); err != nil {
return err
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment