Q: Piping Commands Fails with Exit Status 1
When attempting to pipe commands using exec.Command(), the following error occurs:
ps, "cax | grep myapp"
Why does this command fail while ps cax works?
A: Idiomatic Piping with exec.Command()
Passing the entire command to bash can resolve the issue, but there is a more idiomatic solution:
Code Example:
package main import ( "fmt" "os/exec" ) func main() { grep := exec.Command("grep", "redis") ps := exec.Command("ps", "cax") // Connect ps's stdout 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)) }
Explanation:
The above is the detailed content of Why Does Piping Commands in Go's `exec.Command()` Fail, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!