When using exec.Command() to execute commands in Go, piping the output of one command to another can be challenging.
Consider the following example:
out, err := exec.Command("ps", "cax").Output() // Works and prints command output
However, when attempting to pipe the output of ps to grep, the command fails with an exit status of 1:
out, err := exec.Command("ps", "cax | grep myapp").Output() // Fails
To resolve the issue, a more idiomatic approach is to use exec.Command() for each command and connect their standard input/output streams directly. Here's how:
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 // Start ps first. ps.Start() // Run and get the output of grep. res, _ := grep.Output() fmt.Println(string(res)) }
This allows you to execute multiple commands and pipe their inputs and outputs as needed, providing a flexible way to handle command chains.
The above is the detailed content of How to Properly Pipe Command Outputs in Go's `exec.Command()`?. For more information, please follow other related articles on the PHP Chinese website!