GolangWebDev
GolangWebDev
175 0 0

Pipe output from one shell command to another using golang

You want to execute one shell command with os.Exec() function, wait for it to complete and then pipe the output to another shell command. In Unix/Linux, this is something similar to... for example:

cat test.log | grep ffmpeg

Use the io.Pipe() function to pipe output from the first executed command to the second executing command. For example :

package main

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

func main() {
	first := exec.Command("cat", "text.log")
	second := exec.Command("grep", "ffmpeg")

	// Calling Pipe method
	reader, writer := io.Pipe()

	// push first command output to writer
	first.Stdout = writer

	// read from first command output
	second.Stdin = reader

	// prepare a buffer to capture the output
	// after second command finished executing
	var buff bytes.Buffer
	second.Stdout = &buff

	first.Start()
	second.Start()
	first.Wait()
	writer.Close()
	second.Wait()

	// Prints the data in buffer
	fmt.Printf("Found the text ffmpeg : %s", buff.String())

}
0

See Also


Discussion

Login Topics