Getting the Exit Code in Go
Executing commands on the operating system using the os/exec package provides a convenient way to interact with external processes. However, obtaining the exit code of an executed command can be a challenge at first.
To resolve this issue, one approach is to monitor if the cmd.Wait() function returns nil, which indicates an exit code of 0. However, accessing the specific exit code in case of an error can be more complex.
Platform-Specific Exit Code Retrieval
Unfortunately, there is no cross-platform mechanism to retrieve the exit code for error cases. The following workaround specifically addresses Linux systems:
import ( "os/exec" "log" "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 { log.Printf("Exit Status: %d", exiterr.ExitCode()) } else { log.Fatalf("cmd.Wait: %v", err) } } }
This approach utilizes the syscall package to cast the error to an *exec.ExitError type, allowing access to the exit code.
Documentation Exploration
Referencing the API documentation of the os/exec package can provide further insights into this topic.
The above is the detailed content of How to Retrieve the Exit Code of an Executed Command in Go?. For more information, please follow other related articles on the PHP Chinese website!