Skip to content

Instantly share code, notes, and snippets.

@umutbasal
Created May 8, 2022 00:57
Show Gist options
  • Save umutbasal/42a3331280ae3e68ba99116c001bb69c to your computer and use it in GitHub Desktop.
Save umutbasal/42a3331280ae3e68ba99116c001bb69c to your computer and use it in GitHub Desktop.
prefix executed commands output
package main
import (
"bufio"
"context"
"fmt"
"io"
"os/exec"
)
func prefix(s string) string {
return "prefix: " + s
}
func main() {
reader, writer := io.Pipe()
ctx, cancel := context.WithCancel(context.Background())
scannerStopped := make(chan struct{})
go func() {
defer close(scannerStopped)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
fmt.Println(prefix(scanner.Text()))
}
}()
cmd := exec.Command("cat", "main.go")
cmd.Stdout = writer
_ = cmd.Start()
go func() {
_ = cmd.Wait()
cancel()
writer.Close()
}()
<-ctx.Done()
<-scannerStopped
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment