Golang Runs the Linux command

To Start the command, create a value of type exec.Cmd, then execute the Start method of that type, and get the output pipe of the command, which is of type IO.ReadCloser, and get the output 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())
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish