Created
January 20, 2020 23:37
-
-
Save dantheman213/d6186b7e474b16c7204e36c04c1ac917 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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