bash Go:执行bash脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27765143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Go: execute bash script
提问by user3918985
How do I execute a bash script from my Go program? Here's my code:
如何从 Go 程序执行 bash 脚本?这是我的代码:
Dir Structure:
目录结构:
/hello/
public/
js/
hello.js
templates
hello.html
hello.go
hello.sh
hello.go
你好去
cmd, err := exec.Command("/bin/sh", "hello.sh")
if err != nil {
fmt.Println(err)
}
When I run hello.go and call the relevant route, I get this on my console:
当我运行 hello.go 并调用相关路由时,我在控制台上得到了这个:
exit status 127
output is
exit status 127
output is
I'm expecting ["a", "b", "c"]
我期待 ["a", "b", "c"]
I am aware there is a similar question on SO: Executing a Bash Script from Golang, however, I'm not sure if I'm getting the path correct. Will appreciate help!
我知道 SO: Executing a Bash Script from Golang上有一个类似的问题,但是,我不确定我的路径是否正确。将不胜感激帮助!
回答by Drew
exec.Command()
returns a struct that can be used for other commands like Run
exec.Command()
返回一个可用于其他命令的结构,如 Run
If you're only looking for the output of the command try this:
如果您只是在寻找命令的输出,请尝试以下操作:
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
out, err := exec.Command("date").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)
}
回答by Dario Filipovi?
You can also use CombinedOutput() instead of Output(). It will dump standard error result of executed command instead of just returning error code. See: How to debug "exit status 1" error when running exec.Command in Golang
您还可以使用 CombinedOutput() 而不是 Output()。它将转储执行命令的标准错误结果,而不仅仅是返回错误代码。请参阅: 如何在 Golang 中运行 exec.Command 时调试“退出状态 1”错误
回答by Kul
Check the example at http://golang.org/pkg/os/exec/#Command
检查http://golang.org/pkg/os/exec/#Command 上的示例
You can try by using an output buffer and assigning it to the Stdout of the cmd you create, as follows:
您可以尝试使用输出缓冲区并将其分配给您创建的 cmd 的 Stdout,如下所示:
var out bytes.Buffer
cmd.Stdout = &out
You can then run the command using
然后,您可以使用以下命令运行命令
cmd.Run()
If this executes fine (meaning it returns nil), the output of the command will be in the out
buffer, the string version of which can be obtained with
如果这执行得很好(意味着它返回 nil),命令的输出将在out
缓冲区中,其字符串版本可以通过
out.String()