How to print buffer to stdout but also capture as string?

Issue

I know how to capture the output of a exec.Command but I would like to also stream it to stdout while still capturing it.
Thanks for any input!

package main

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

func main() {
    cmd := exec.Command("ls")
    var out bytes.Buffer
    cmd.Stdout = &out
    cmd.Run()
    fmt.Println(out.String())
}

Solution

Example using io.MultiWriter

package main

import (
    "io"
    "os"
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls")
    var out bytes.Buffer
    w := io.MultiWriter(os.Stdout, &out)
    cmd.Stdout = w
    fmt.Printf("===Stdout:===\n")
    cmd.Run()
    fmt.Printf("\n===Variable:===\n")
    fmt.Println(out.String())
}

Answered By – Chandan

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.