Get exit code - Go

前端 未结 4 421
梦毁少年i
梦毁少年i 2020-12-04 13:52

I\'m using the package: os/exec http://golang.org/pkg/os/exec/ to execute a command in the operating system but I don\'t seem to find the way to get the exit code. I can rea

4条回答
  •  攒了一身酷
    2020-12-04 14:35

    It's easy to determine if the exit code was 0 or something else. In the first case, cmd.Wait() will return nil (unless there is another error while setting up the pipes).

    Unfortunately, there is no platform independent way to get the exit code in the error case. That's also the reason why it isn't part of the API. The following snippet will work with Linux, but I haven't tested it on other platforms:

    package main
    
    import "os/exec"
    import "log"
    import "syscall"
    
    func main() {
        cmd := exec.Command("git", "blub")
    
        if err := cmd.Start(); err != nil {
            log.Fatalf("cmd.Start: %v", err)
        }
    
        if err := cmd.Wait(); err != nil {
            if exiterr, ok := err.(*exec.ExitError); ok {
                // The program has exited with an exit code != 0
    
                // This works on both Unix and Windows. Although package
                // syscall is generally platform dependent, WaitStatus is
                // defined for both Unix and Windows and in both cases has
                // an ExitStatus() method with the same signature.
                if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
                    log.Printf("Exit Status: %d", status.ExitStatus())
                }
            } else {
                log.Fatalf("cmd.Wait: %v", err)
            }
        }
    }
    

    Just follow the api docs to find out more :)

提交回复
热议问题