How to execute linux commands in go

PHPz
Release: 2023-05-13 15:10:17
forward
2446 people have browsed it

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())
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template