First create a value of type exec.Cmd, and then execute the Start method of this type to start the command and obtain the output pipe of this command. The pipe type is io.ReadCloser, and the output content is obtained through the pipe.
package main import ( "bytes" "fmt" "io" "os/exec" ) func main() { cmd0 := exec.Command("echo", "-n", "my first command") //启动命令 if err := cmd0.Start(); err != nil { fmt.Printf("command can not start %s \n", err) return } //获取输出管道 stdout0, err := cmd0.StdoutPipe() if err != nil { fmt.Printf("couldn't stdout pipe for command %s \n", err) return } var outputBuf0 bytes.Buffer for { tempOutput := make([]byte, 2048) n, err := stdout0.Read(tempOutput) if err != nil { if err == io.EOF { break } else { fmt.Printf("couldn't read data from pip %s \n", err) return } } if n > 0 { outputBuf0.Write(tempOutput[:n]) } } fmt.Printf("%s\n", outputBuf0.String()) }
The above is the detailed content of How to execute linux commands in go. For more information, please follow other related articles on the PHP Chinese website!