Home > Backend Development > Golang > How to Retrieve the Exit Code of an Executed Command in Go?

How to Retrieve the Exit Code of an Executed Command in Go?

Patricia Arquette
Release: 2024-12-16 19:18:13
Original
495 people have browsed it

How to Retrieve the Exit Code of an Executed Command in Go?

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)
        }
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template