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

wai*_*ani 3 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)
Run Code Online (Sandbox Code Playgroud)

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

Sea*_*ean 6

如果您想执行多个命令,尤其是一次执行多个命令,bash 并不是最好的方法。使用os/exec和 goroutine。

如果您确实想运行 bash 脚本,这里有一个使用os/exec. 我假设您想查看 bash 脚本的输出,而不是保存并处理它(但您可以使用 轻松做到这一点bytes.Buffer)。为了简洁起见,我在这里删除了所有错误检查。带错误检查的完整版本在这里

包主

进口 (
        “字节”
        “io”
        “文本/模板”
        “操作系统”
        “操作系统/执行”
        “同步”
)

函数主() {
        var tmp = template.Must(template.New("").Parse(`
回声{{.名称}}
回声{{.姓氏}}
`[1:]))

        var 脚本 bytes.Buffer
        tmp.Execute(&script, 结构 {
                名称字符串
                姓氏字符串
        {“詹姆斯”,“迪恩”})

        bash := exec.Command("bash")
        stdin, _ := bash.StdinPipe()
        stdout, _ := bash.StdoutPipe()
        stderr, _ := bash.StderrPipe()

        等待 := 同步.WaitGroup{}
        等待.添加(3)
        去功能(){
                io.Copy(stdin,&script)
                标准输入.Close()
                等待.完成()
        }()
        去功能(){
                io.Copy(os.Stdout, stdout)
                等待.完成()
        }()
        去功能(){
                io.Copy(os.Stderr, stderr)
                等待.完成()
        }()

        bash.Start()
        等等()
        bash.Wait()
}