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

How to Retrieve the Exit Code of a System Command in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 07:59:32154browse

How to Retrieve the Exit Code of a System Command in Go?

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!

Statement:
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