Go - Combining cmd.StdoutPipe and Cmd.StderrPipe

Viewed 2582

I would like to execute a command in Go, and combining its stdout and stderr into one stream. I wrote this code, its read only from the stdout, but I don't know how to I combine it with the stderr:

package main

import (
    "fmt"
    "os"
    "os/exec"
    "bufio"
)

func runCommand() {
    var (
        err error
    )

    cmdName := "docker"
    cmdArgs := []string{"build", "--no-cache=true", "--force-rm=true", "."}

    cmd := exec.Command(cmdName, cmdArgs...)

    cmdReader, err := cmd.StdoutPipe()
    if err != nil {
        fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
    }

    scanner := bufio.NewScanner(cmdReader)
    go func() {
        for scanner.Scan() {
            fmt.Printf("docker build out | %s\n", scanner.Text())
        }
    }()

    err = cmd.Start()
    if err != nil {
        fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
    }

    err = cmd.Wait()
    if err != nil {
        fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
    }
}

func main() {
    runCommand()
}

Thanks for all answers!

2 Answers
Related