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
+8.3k Golang : How to get ECDSA curve and parameters data?
+13.3k Golang : How to filter a map's elements for faster lookup
+19.7k Golang : How to read float value from standard input ?
+12.5k Golang : Check if an integer is negative or positive
+5.7k Get Facebook friends working in same company
+9.2k Golang : cannot assign type int to value (type uint8) in range error
+6.9k Golang : Configure Apache and NGINX to access your Go service example
+13.4k Golang : Submit web forms without browser by http.PostForm example
+6.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+7.5k Golang : Another camera capture GUI application with GTK and OpenCV
+9.3k Generate Random number with math/rand in Go
+50.4k Golang : How to get struct field and value by name