Home >Backend Development >Golang >How Can I Retrieve the Exit Code of an External Command in Go?
How to Retrieve Exit Code in Go
When utilizing the os/exec package to execute commands in the operating system, individuals often encounter difficulties retrieving the exit code. While reading the output is possible through capturing the stdout, obtaining the exit code remains a challenge.
Solution:
The determination of whether the exit code is 0 or not can be achieved through cmd.Wait(), which returns nil in the case of a successful exit. However, when the exit code is non-zero, obtaining it can become more intricate. This is due to the platform-dependent nature of exit code retrieval.
Platform-Specific Approach for Linux:
Although there is no cross-platform approach for retrieving exit codes, the following snippet can be employed on Linux systems:
import "syscall" 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 { log.Printf("Exit Status: %d", exiterr.ExitCode()) } else { log.Fatalf("cmd.Wait: %v", err) } }
This method allows for the retrieval of exit codes specific to Linux systems. However, it is crucial to note that this approach may not be universally applicable.
Additional Resources:
Further information regarding exit code handling in Go can be found in the package documentation:
[os/exec - Process Management](https://golang.org/pkg/os/exec/)
The above is the detailed content of How Can I Retrieve the Exit Code of an External Command in Go?. For more information, please follow other related articles on the PHP Chinese website!