5

I have the following code which outputs data from stdout to a file:

cmd := exec.Command("ls","lh")
outfile, err := os.Create("./out.txt")
if err != nil {
    panic(err)
}
defer outfile.Close()

stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
    panic(err)
}

writer := bufio.NewWriter(outfile)
defer writer.Flush()

err = cmd.Start()
if err != nil {
    panic(err)
}

go io.Copy(writer, stdoutPipe)
cmd.Wait()

I need to get the output from stdout into a string value instead of a file. How do I achieve that?

Is there perhaps another function that will allow me to change the io.Copy line to go io.Copy(myStringVariable, stdoutPipe) as I need to read the output of the command and apply some processing to it?

Thanks in advance

1
  • You could have just assigned the file as the command's Stdout and avoided the pipe and copy goroutine (in which you were losing your read/write errors), Commented Sep 13, 2016 at 20:15

2 Answers 2

14

You don't need the pipe, writer, goroutine, etc. Just use Cmd.Output

out, err := exec.Command("ls","lh").Output()

You can convert the output []byte to a string as needed with string(out)

Sign up to request clarification or add additional context in comments.

1 Comment

Short and sweet! Thanks
6

You can set the file as the command's stdout

f, err := os.Create("./out.txt")
if err != nil {
    panic(err)
}
defer f.Close()

cmd := exec.Command("ls", "-lh")
cmd.Stdout = f
cmd.Stderr = os.Stderr

if err := cmd.Run(); err != nil {
    panic(err)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.