The following works and prints the command output:
out, err := exec.Command("ps", "cax").Output()
but this one fails (with exit status 1):
out, err := exec.Command("ps", "cax | grep myapp").Output()
Any suggestions?
Passing everything to bash
works, but here's a more idiomatic way of doing it.
package main
import (
"fmt"
"os/exec"
)
func main() {
grep := exec.Command("grep", "redis")
ps := exec.Command("ps", "cax")
// Get ps's stdout and attach it to grep's stdin.
pipe, _ := ps.StdoutPipe()
defer pipe.Close()
grep.Stdin = pipe
// Run ps first.
ps.Start()
// Run and get the output of grep.
res, _ := grep.Output()
fmt.Println(string(res))
}
You could do:
out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output()
In this specific case, you don't really need a pipe, a Go can grep
as well:
package main
import (
"bufio"
"bytes"
"os/exec"
"strings"
)
func main() {
c, b := exec.Command("go", "env"), new(bytes.Buffer)
c.Stdout = b
c.Run()
s := bufio.NewScanner(b)
for s.Scan() {
if strings.Contains(s.Text(), "CACHE") {
println(s.Text())
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With