Get exit code - Go

前端 未结 4 424
梦毁少年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:43

    September 2019, Go 1.13 introduced errors.As which supports error "unwrapping" - handy for finding precise errors in a nested call-chain.

    So to extract and inspect the two most common errors when running an external command:

    • os.PathError
    • exec.ExitError

    err := cmd.Run()
    
    var (
        ee *exec.ExitError
        pe *os.PathError
    )
    
    if errors.As(err, &ee) {
        log.Println("exit code error:", ee.ExitCode()) // ran, but non-zero exit code
    
    } else if errors.As(err, &pe) {
        log.Printf("os.PathError: %v", pe) // "no such file ...", "permission denied" etc.
    
    } else if err != nil {
        log.Printf("general error: %v", err) // something really bad happened!
    
    } else {
        log.Println("success!") // ran without error (exit code zero)
    }
    

提交回复
热议问题