How to Pipe Commands Together in Go

Connect Go command outputs to inputs manually using io.Pipe since shell-style piping is not supported.

Go does not support shell-style piping between commands; instead, you must manually connect the Stdout of one exec.Cmd to the Stdin of another using io.Pipe. Create a pipe, assign its writer to the first command's Stdout and its reader to the second command's Stdin, then run both commands.

import (
	"io"
	"os/exec"
)

// Command 1: produces output
cmd1 := exec.Command("ls", "-l")

// Command 2: consumes input
cmd2 := exec.Command("grep", "test")

// Create the pipe
pipeReader, pipeWriter := io.Pipe()

// Connect cmd1 output to pipe input
cmd1.Stdout = pipeWriter

// Connect pipe output to cmd2 input
cmd2.Stdin = pipeReader

// Start both commands
cmd1.Start()
cmd2.Start()

// Wait for cmd1 to finish, then close the pipe writer
cmd1.Wait()
pipeWriter.Close()

// Wait for cmd2 to finish
cmd2.Wait()