转到:将bash脚本嵌入二进制文件

I'm trying to cross compile a Go program that will execute a bash script. Is it possible to embed the bash script in the binary?

I've referenced: Golang serve static files from memory

Not sure if this applies to executing bash scripts though. Am I missing something here? Some clarification or pointers will be very helpful, thanks!

Yes, you can include any files in your binary with go-bindata: https://github.com/jteeuwen/go-bindata

I've also made a tool for making Go/Bash hybrid apps: https://github.com/progrium/go-basher

Did you try writing the stream-data (according to the reference go-bindata provides a function that returns []byte) into a temporary file?

see: http://golang.org/pkg/io/ioutil/#TempFile

you can then execute it with a syscall

http://golang.org/pkg/syscall/#Exec

where the first argument needs to be a shell.

If you really have to do this, just construct a script and pass it as Stdin; here's an example out in the wild:

https://github.com/GoogleCloudPlatform/kubernetes/blob/63248f281f55698b520137d477631e87a3b02c4f/hack/e2e.go#L420

You can actually directly interface with the system shell in Go. Depending on what's in your bash script you can probably convert everything completely to go. For example things like handling files, extracting archives, outputting text, asking for user input, downloading files, and so much more can be done natively in Go. For anything you absolutely need the shell for you can always use golang.org/pkg/os/exec.

I wrote a snippet that demonstrates a really simple Go based command shell. Basically it pipes input, output, and error between the user and the shell. It can be used interactively or to directly run most shell commands. I'm mentioning it here mostly to demonstrate Go's OS capabilities. Check it out: github.com/lee8oi/goshell.go