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

时间:2014-08-13 03:50:42

标签: go

鉴于以下内容:

   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)

是否有一个魔术函数将字符串作为一个bash脚本执行? “os / exec”.Command一次只能执行一个命令。

2 个答案:

答案 0 :(得分:4)

如果要执行多个命令,特别是一次执行多个命令,bash不是执行此操作的最佳方法。使用os/exec和goroutines。

如果您真的想要运行bash脚本,请使用os/exec作为示例。我假设您想要查看bash脚本的输出,而不是保存并处理它(但您可以使用bytes.Buffer轻松完成此操作)。为简洁起见,我已在此处删除了所有错误检查。 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 :(得分:-1)

使用bash -c ... exec.Command("bash", "-c", bashScript)