Nginx版本命令没有return版本也不报错

Nginx version command does not return version nor error

我正在尝试使用 Go 检查我的计算机上安装了哪个版本的 Nginx。

这是我的代码片段:

package main

import (
    "bytes"
    "errors"
    "fmt"
    "os/exec"
)

func runCommand(command string, arg ...string) (string, error) {
    cmd := exec.Command(command, arg...)
    cmdOutput := &bytes.Buffer{}
    errOutput := &bytes.Buffer{}
    cmd.Stdout = cmdOutput
    cmd.Stderr = errOutput
    err := cmd.Run()
    if err != nil {
        return "", errors.New(string(errOutput.Bytes()))
    }
    fmt.Println("Command succeeded")
    return string(cmdOutput.Bytes()), nil
}

func getVersion(command string, arg ...string) {
    path, err := exec.LookPath(command)
    if err != nil {
        fmt.Println("No path for " + command + " found")
        return
    }
    fmt.Println("Path for " + command + " is " + path)

    result, err := runCommand(path, arg...)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(command + " version is: " + result)
}

func main() {
    getVersion("go", "version") // works
    getVersion("nginx", "-v") // does not work
    getVersion("firefox", "-v") // works
}

对于 Go 和 Firefox 它工作得很好,但是对于 Nginx 它return既不是版本也不是错误。好像是return一个空字符串...

查看权限: Firefox 文件是 root:root 拥有的 sh 文件的符号链接,权限为 755。 Nginx 文件由 root:root 所有,权限也为 755。

当然,运行命令nginx -v有效。

您期待标准输出的输出。它正在打印到 stderr。尝试 cmd.CombinedOutput()