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
+15.3k Golang : Accurate and reliable decimal calculations
+5.1k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+19.2k Golang : Check whether a network interface is up on your machine
+24k Golang : Fix type interface{} has no field or no methods and type assertions example
+9.1k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+9.5k Android Studio : Indicate progression with ProgressBar example
+15.3k Golang : Get HTTP protocol version example
+5.2k Responsive Google Adsense
+4.6k Javascript : Detect when console is activated and do something about it
+29.9k Golang : Get and Set User-Agent examples
+7.5k Golang : How to detect if a sentence ends with a punctuation?
+5.7k Golang : Struct field tags and what is their purpose?