Golang can invoke commands in Linux via the [os/exec] package, however, for pipelines in Linux ("|" ) but cannot be used directly. So the interface for writing a pipe is as follows.
Func pipline (Cmds ... *exec. CMD) ([]byte, []byte, error) { //At least one command ifLen (CMDS) <1 { returnNil , nil, nil}varoutput bytes. Buffervarstderr bytes. BuffervarErr error Maxindex:= Len (CMDS)-1Cmds[maxindex]. Stdout= &output CMDS[MAXINDEX]. Stderr= &stderr forI, cmd: =Range Cmds[:maxindex] {ifi = =Maxindex { Break} cmds[i+1]. Stdin, err =cmd. Stdoutpipe ()ifErr! =Nil {returnNil, nil, err}} //Start each command for_, cmd: =range Cmds {err:=cmd. Start ()ifErr! =Nil {returnoutput. Bytes (), stderr. Bytes (), err}}//Wait for each command to complete for_, cmd: =range Cmds {err:=cmd. Wait ()ifErr! =Nil {returnoutput. Bytes (), stderr. Bytes (), err}}returnoutput. Bytes (), stderr. Bytes (), nil}
View Code
Interface Invocation Method:
//Linux COMAND:DF | grep-w "/" | cut-d "%",-F 1DF: = Exec.command ("DF") grep:= Exec.command ("grep","- W","/") Cut:= Exec.command ("Cut","- D","%","- F","1") result, _, Err:=Utils. Pipline (DF, grep, cut)ifErr! =Nil {log. Error (ERR)return } //Output Final ResultFmt. Println (string(result))
View Code
Golang+linux+pipline