How to Get Exit Code Using Go
In Go, the os/exec package provides the means to execute system commands. However, retrieving the exit code poses a challenge.
Retrieve Exit Code on Success
When a command exits with exit code 0, the cmd.Wait() function returns nil.
Retrieve Exit Code on Failure (for Linux Only)
For Linux systems, the following code snippet demonstrates how to obtain the exit code when the command fails:
import ( "fmt" "log" "os/exec" "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 { fmt.Printf("Exit Status: %d", exiterr.ExitCode()) } else { log.Fatalf("cmd.Wait: %v", err) } } }
No Cross-Platform Approach
Unfortunately, there is no cross-platform method to retrieve the exit code on failure. The os/exec API lacks this functionality by design.
Additional Resource
This comprehensive article elaborates on this topic and provides additional technical details: http://golang.org/pkg/os/exec/
The above is the detailed content of How to Retrieve the Exit Code of a System Command in Go?. For more information, please follow other related articles on the PHP Chinese website!