2016-12-08 8 views
0

次作品が含まれており、コマンドの出力を印刷し、実行コマンド:ゴーexec.Command() - パイプ

out, err := exec.Command("ps", "cax").Output() 

が、この1つは(終了ステータス1で)失敗します。

out, err := exec.Command("ps", "cax | grep myapp").Output() 

どれでも提案?すべてを渡す

out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output() 

答えて

5

あなたが行うことができます。

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)) 
} 
6

bashに作品を、しかし、ここでそれを行うためのより多くの慣用的な方法があります: