Use exec.Command to execute a command with a pipe

didi12468
Feb 12, 2022

--

In Go, when we want to execute a command with a pipe (such as: ps aux|grep go), we can’t directly like the following:

Doing so will not produce any output.

There are two ways to do it:

  1. Use the command: sh -c ""

This is the recommended practice.
If the output is not a lot, it is recommended to use the github.com/go-cmd/cmd library to execute system commands, such as:

2. Use io.Pipe() to connect two commands

The second method is very inconvenient and cannot use grep.Stdout(), grep.StdoutPipe() to get the output.

--

--