doujiao8649 2014-08-13 03:50
浏览 45
已采纳

Golang:将文本/模板作为bash脚本执行

Given the following:

   import(
   "bytes"
   "code.google.com/p/go/src/pkg/text/template"
   )

   ....

   var tmp = template.Must(template.New("").Parse(`
   echo {{.Name}}
   echo {{.Surname}}
   `[1:]))

   var buf bytes.Buffer
   tmp.Execute(&buf, struct{Name string, Surname: string}{"James","Dean"})
   bashScript = string(buf)

   // Now, how do I execute the bash script?
   magic.Execute(bashScript)

Is there a magic function that will execute the string as one bash script? "os/exec".Command can execute only one command at a time.

  • 写回答

2条回答 默认 最新

  • douchuilai2355 2014-08-13 05:15
    关注

    If you want to execute more than one command, especially more than one at a time, bash is not the best way to do that. Use os/exec and goroutines.

    If you really want to run a bash script, here's an example using os/exec. I assumed you wanted to see the output of the bash script, rather than save it and process it (but you can easily do that with a bytes.Buffer). I've removed all the error checking here for brevity. The full version with error checking is here.

    package main
    
    import (
            "bytes"
            "io"
            "text/template"
            "os"
            "os/exec"
            "sync"
    )
    
    func main() {
            var tmp = template.Must(template.New("").Parse(`
    echo {{.Name}}
    echo {{.Surname}}
    `[1:]))
    
            var script bytes.Buffer
            tmp.Execute(&script, struct {
                    Name    string
                    Surname string
            }{"James", "Dean"})
    
            bash := exec.Command("bash")
            stdin, _ := bash.StdinPipe()
            stdout, _ := bash.StdoutPipe()
            stderr, _ := bash.StderrPipe()
    
            wait := sync.WaitGroup{}
            wait.Add(3)
            go func () {
                    io.Copy(stdin, &script)
                    stdin.Close()
                    wait.Done()
            }()
            go func () {
                    io.Copy(os.Stdout, stdout)
                    wait.Done()
            }()
            go func () {
                    io.Copy(os.Stderr, stderr)
                    wait.Done()
            }()
    
            bash.Start()
            wait.Wait()
            bash.Wait()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器