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
+5.8k Golang : Generate multiplication table from an integer example
+15.4k Golang : rune literal not terminated error
+7k Golang : Gorrila mux.Vars() function example
+12.7k Golang : http.Get example
+8k Golang : Routes multiplexer routing example with regular expression control
+5.9k Linux/MacOSX : Search for files by filename and extension with find command
+14.7k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+8.9k Golang : Capture text return from exec function example
+17.9k Golang : Check if a directory exist or not
+25.8k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+6k Golang : Create new color from command line parameters
+8.7k Android Studio : Image button and button example