golang+linux+pipline
golang里可以通过[os/exec]包调用linux里的命令,然而对于linux里的管道(“|”)却不能直接使用。所以写了一个管道的接口如下。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
func Pipline(cmds ...*exec.Cmd) ([]byte, []byte, error) { // At least one command if len(cmds) < 1 { return nil, nil, nil } var output bytes.Buffer var stderr bytes.Buffer var err error maxindex := len(cmds) - 1 cmds[maxindex].Stdout = &output cmds[maxindex].Stderr = &stderr for i, cmd := range cmds[:maxindex] { if i == maxindex { break } cmds[i+1].Stdin, err = cmd.StdoutPipe() if err != nil { return nil, nil, err } } // Start each command for _, cmd := range cmds { err := cmd.Start() if err != nil { return output.Bytes(), stderr.Bytes(), err } } // Wait for each command to complete for _, cmd := range cmds { err := cmd.Wait() if err != nil { return output.Bytes(), stderr.Bytes(), err } } return output.Bytes(), stderr.Bytes(), nil }
接口调用方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// linux comand: df | grep -w "/" | cut -d "%", -f 1 df := exec.Command("df") grep := exec.Command("grep", "-w", "/") cut := exec.Command("cut", "-d", "%", "-f", "1") result, _, err := utils.Pipline(df, grep, cut) if err != nil { log.Error(err) return } // 输出最终结果 fmt.Println(string(result))