Skip to content

Instantly share code, notes, and snippets.

@dantheman213
Created January 20, 2020 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dantheman213/d6186b7e474b16c7204e36c04c1ac917 to your computer and use it in GitHub Desktop.
Save dantheman213/d6186b7e474b16c7204e36c04c1ac917 to your computer and use it in GitHub Desktop.
// https://www.reddit.com/r/golang/comments/1hvvnn/any_better_way_to_do_a_crossplatform_exec_and/
func GetCommandResult(cmd *exec.Cmd) ([]byte, int, error) {
output, err := cmd.CombinedOutput()
if err != nil {
if e2, ok := err.(*exec.ExitError); ok {
if status, ok := e2.Sys().(syscall.WaitStatus); ok && runtime.GOOS == "windows" {
s := reflect.ValueOf(&status).Elem()
for i := 0; i < s.NumField(); i++ {
if s.Type().Field(i).Name == "ExitCode" {
// win32
if exitCode, ok := s.Field(i).Interface().(int); ok {
return output, exitCode, nil
}
}
}
} else {
// Linux/everything else
match := regexp.MustCompile(`exit status (\d+)`).FindStringSubmatch(err.Error())
if len(match) == 0 {
panic("exotic operating system detected. ABORT! ABORT!")
}
exitCode, _ := strconv.Atoi(match[1])
return output, exitCode, nil
}
}
fmt.Println(err)
}
return output, 0, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment