golanggit cloneexec.Command
func RunCommand(path, name string, arg ...string) (msg string, err error) {
cmd := exec.Command(name, arg...)
cmd.Dir = path
err = cmd.Run()
log.Println(cmd.Args)
if err != nil {
log.Println("err", err.Error(), "cmd", cmd.Args)
}
return
}
这种写法是没有问题,但是一旦执行出错返回值过于简洁了,比如
func main() {
msg, err := common.RunCommand("./", "/bin/bash", "-c", "git clone url")
if err != nil {
log.Fatal(err)
return
}
log.Println(msg)
}
exit status 128
func RunCommand(path, name string, arg ...string) (msg string, err error) {
cmd := exec.Command(name, arg...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
cmd.Dir = path
err = cmd.Run()
log.Println(cmd.Args)
if err != nil {
msg = fmt.Sprint(err) + ": " + stderr.String()
err = errors.New(msg)
log.Println("err", err.Error(), "cmd", cmd.Args)
}
log.Println(out.String())
return
}
再次执行,返回
2022/04/03 20:33:49 [/bin/bash -c git clone url]
2022/04/03 20:33:49 err exit status 128: fatal: repository 'url' does not exist
cmd [/bin/bash -c git clone url]
2022/04/03 20:33:49
2022/04/03 20:33:49 exit status 128: fatal: repository 'url' does not exist
repository 'url' does not exist
StdoutStderrStdoutStderr