I'm trying to stream the Stdout of a shell command to the console, but am having difficulty.
Here's what I currently have:
cmd := exec.Command("sh", "-c", `for number in {0..10}; do echo "$number "; done;`)
pipe, _ := cmd.StdoutPipe()
reader := bufio.NewReader(pipe)
line, err := reader.ReadString('
')
for err == nil {
fmt.Println(line)
line, err = reader.ReadString('
')
}
I would expect this to print out the numbers 0 through 10, but it seems to hang on line 3 (the first call to ReadString
.
I started with cmd.Output()
and cmd.CombinedOutput()
, but those methods seem to buffer the entire output stream until the command is complete. I need to process the output as it streams, not wait until the command is complete.
I also tried this: continuously reading from exec.Cmd output, but it didn't seem to work and I went away from it because I really want to read lines and not have to manage the buffer manually.
Other things I've looked through: