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
Release: 2024-12-19 07:59:32
Original
155 people have browsed it

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

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!

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