Skip to content

Instantly share code, notes, and snippets.

@SimonBaeumer
Last active January 15, 2020 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimonBaeumer/504e6c7f5747154872c88eb5eb827a48 to your computer and use it in GitHub Desktop.
Save SimonBaeumer/504e6c7f5747154872c88eb5eb827a48 to your computer and use it in GitHub Desktop.
Multiplexed writer in exec.Cmd
package main
import (
"bytes"
"fmt"
"log"
"io"
"os/exec"
)
func main() {
command := `
echo stdout.
echo stdout..
>&2 echo stderr.
>&2 echo stderr..
echo stdout.
echo stdout..
>&2 echo stderr.
>&2 echo stderr..
echo stdout.
echo stdout..
>&2 echo stderr.
>&2 echo stderr..
sleep 1
`
// Create the writer which will be used in stderr and stdout
combinedWriter := &bytes.Buffer{}
// Create multiplexed writer
stdout := MultiplexedWriter{[]io.Writer{combinedWriter}}
stderr := MultiplexedWriter{[]io.Writer{combinedWriter}}
// Execute the command
cmd := exec.Command("/bin/sh", "-c", command)
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
fmt.Printf(combinedWriter.String())
}
// MultiplexedWriter is used to write into multiple writers,
type MultiplexedWriter struct {
writers []io.Writer
}
func (w MultiplexedWriter) Write(p []byte) (n int, err error){
for _, o := range w.writers {
n, err = o.Write(p)
if err != nil {
return 0, fmt.Errorf("Error occured %s", err.Error())
}
}
return n, nil
}
// Result
// stderr.
// stderr..
// stderr.
// stderr..
// stderr.
// stderr..
// stdout.
// stdout..
// stdout.
// stdout..
// stdout.
// stdout..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment