Golang : Pipe output from one os.Exec(shell command) to another command
Problem :
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:
ls | wc -l
Solution :
Use the io.Pipe() function to pipe output from the first executed command to the second executing command. For example :
package main
import (
"bytes"
"io"
"os/exec"
"fmt"
)
func main() {
first := exec.Command("ps", "-ef")
second := exec.Command("wc", "-l")
// http://golang.org/pkg/io/#Pipe
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()
total := buff.String() // convert output to string
fmt.Printf("Total processes running : %s", total)
}
Sample output :
Total processes running : 89
Reference :
See also : Golang : Execute shell command
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.1k Facebook : How to force facebook to scrape latest URL link data?
+4.4k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+7.5k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+5.2k Golang : Calculate a pip value and distance to target profit example
+14k Golang : Image to ASCII art example
+17.2k Golang : How to generate QR codes?
+11.2k Golang : Create S3 bucket with official aws-sdk-go package
+5.1k Python : Convert(cast) bytes to string example
+32.7k Golang : Math pow(the power of x^y) example
+36.5k Golang : Smarter Error Handling with strings.Contains()
+14.8k Golang : How to check if your program is running in a terminal