Skip to content

Instantly share code, notes, and snippets.

@andboson
Created December 18, 2016 18:50
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 andboson/ab06eda41aeae4ef797c469d85e0941d to your computer and use it in GitHub Desktop.
Save andboson/ab06eda41aeae4ef797c469d85e0941d to your computer and use it in GitHub Desktop.
catch_cmd_output
package main
import (
"io"
"os"
"log"
"os/exec"
)
func main() {
pr, pw := io.Pipe()
defer pw.Close()
// tell the command to write to our pipe
cmd := exec.Command("pwd", "lh")
cmd.Stdout = pw
go func() {
defer pr.Close()
// copy the data written to the PipeReader via the cmd to stdout
if _, err := io.Copy(os.Stdout, pr); err != nil {
log.Fatal(err)
}
}()
// run the command, which writes all output to the PipeWriter
// which then ends up in the PipeReader
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment