zet

Replicate unix pipes in Golang

package main

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

func main() {
	// Step 1: Create the `ls` command
	lsCmd := exec.Command("ls")

	// Step 2: Create the `sort` command
	sortCmd := exec.Command("sort")

	// Step 3: Create the `uniq` command
	uniqCmd := exec.Command("uniq")

	// Pipe `ls` output to `sort` input
	sortCmd.Stdin, _ = lsCmd.StdoutPipe()

	// Pipe `sort` output to `uniq` input
	uniqCmd.Stdin, _ = sortCmd.StdoutPipe()

	// Capture the final output of `uniq`
	var uniqOutput bytes.Buffer
	uniqCmd.Stdout = &uniqOutput

	// Start the pipeline commands
	uniqCmd.Start()
	sortCmd.Start()
	lsCmd.Run() // Run `ls` and close its stdout to send EOF to `sort`
	sortCmd.Wait()
	uniqCmd.Wait()

	// Print the output from `uniq`
	fmt.Println(uniqOutput.String())
}