Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Pipe 3 or more commands with os.exec()?

Tags:

go

How can I pipe 3+ commands together in Go (for example ls | grep | wc)? I've tried to modify this code that is for piping 2 commands, but can't figure out the correct way.,

package main

import (
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    c2 := exec.Command("wc", "-l")
    c2.Stdin, _ = c1.StdoutPipe()
    c2.Stdout = os.Stdout
    _ = c2.Start()
    _ = c1.Run()
    _ = c2.Wait()
}

https://stackoverflow.com/a/10953142/3761308

like image 791
user3761308 Avatar asked Oct 27 '25 09:10

user3761308


1 Answers

package main

import (
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    c2 := exec.Command("grep", "-i", "o")
    c3 := exec.Command("wc", "-l")
    c2.Stdin, _ = c1.StdoutPipe()
    c3.Stdin, _ = c2.StdoutPipe()
    c3.Stdout = os.Stdout
    _ = c3.Start()
    _ = c2.Start()
    _ = c1.Run()
    _ = c2.Wait()
    _ = c3.Wait()
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!