原文鏈接 : https://www.ikaze.cn/article/44
在go中我們想執行帶管道的命令時(如:ps aux|grep go
),不能直接像下面這樣:
exec.Command("ps", "aux", "|", "grep", "go")
這樣做不會有任何輸出。
有兩種方法可以做到:
-
使用
sh -c ""
命令exec.Command("bash", "-c", "ps aux|grep go")
這是推薦的做法。
如果輸出不是很多,推薦使用github.com/go-cmd/cmd
庫來執行系統命令,如:import "github.com/go-cmd/cmd" c := cmd.NewCmd("bash", "-c", "ps aux|grep go") <-c.Start() fmt.Println(c.Status().Stdout)
-
使用
io.Pipe()
連接兩個命令ps := exec.Command("ps", "aux") grep := exec.Command("grep", "go") r, w := io.Pipe() // 創建一個管道 defer r.Close() defer w.Close() ps.Stdout = w // ps向管道的一端寫 grep.Stdin = r // grep從管道的一端讀 var buffer bytes.Buffer grep.Stdout = &buffer ps.Start() grep.Start() ps.Wait() w.Close() grep.Wait() io.Copy(os.Stdout, &buffer)
第二種方法非常不方便,而且無法使用
grep.Stdout()
,grep.StdoutPipe()
獲取輸出