title: Go执行系统命令并获取退出代码
date: 2022-11-29 09:37:01.0
updated: 2022-11-29 09:37:01.0
url: https://liumou.site/doc/577
categories:

  • GO
    tags:
  • Go

package main

import (
    "fmt"
    "os/exec"

    "gitee.com/liumou_site/logger"
)

func main() {
    // 正常命令
    r := exec.Command("ipconfig")
    err := r.Run()
    if err != nil {
        fmt.Println("Err: ", err)
        // r.CombinedOutput()
    }
    logger.Debug("错误代码: ", r.ProcessState.ExitCode())

    // 错误命令

    ru := exec.Command("ipconfigs")
    rur := ru.Run()
    if rur != nil {
        fmt.Println("Err: ", rur)
        // r.CombinedOutput()
    }
    logger.Debug("错误代码: ", ru.ProcessState.ExitCode())
}

效果

[Running] go run "d:\data\git\Go\demo\r.go"
[2022-11-29 09:33:29] [DEBG] [r.go:18] 错误代码:  0
Err:  exec: "ipconfigs": executable file not found in %PATH%
[2022-11-29 09:33:30] [DEBG] [r.go:28] 错误代码:  -1

[Done] exited with code=0 in 2.888 seconds