2016-12-08 1 views
0

다음 작품을 포함하고 명령 출력 인쇄 :이동 exec.Command() - 실행 명령 파이프

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

을하지만,이 하나 (종료 상태 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에 일을하지만, 여기에 그 일을 좀 더 관용적 방법이있다 :