Taku
Taku

Reputation: 5927

Pipe multiple commands then write to file

I'm trying to pipe multiple *exec.Cmd and then write to file. When I try with one cmd and output to file, it writes to the file. However, when I try with multiple commands and output to file, it does not. But the exec.Cmd seems to be piping as it can stdout correctly.

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

c1 := exec.Command("sh", "-c", "while sleep 1; do echo test; done")
c1.Stdout = outfile
_ = c1.Run()

for {

}

This above code writes to file every one second. But when I try this:

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

c1 := exec.Command("sh", "-c", "while sleep 1; do echo test; done")
c2 := exec.Command("grep", "t")
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = outfile
_ = c2.Start()
_ = c1.Run()
c2.Wait()

This does not output anything.

But when I change c2.Stdout = outfile to c2.Stdout = os.Stdout, then it prints out the output correctly

I can't figure out why this is happening. Any help appreciated.

Upvotes: 0

Views: 231

Answers (1)

Taku
Taku

Reputation: 5927

So, the grep is not noticing that it's writing to a regular file.

By changing this line from:

c2 := exec.Command("grep", "t")

to this works and writes to the file correctly

c2 := exec.Command("grep", "t", "--line-buffered")

Upvotes: 1

Related Questions