go - Nginx version 命令不返回版本也不返回错误

标签 go command

我正在尝试使用 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,它既不返回版本也不返回错误。它似乎返回一个空字符串...

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

当然,运行命令 nginx -v 是可行的。

最佳答案

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

关于go - Nginx version 命令不返回版本也不返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57731024/

相关文章:

linux - Unix 中 "cat -A"命令选项是什么意思

function - golang : http. get() 返回

regex - 戈朗 : Remove all characters except | from string

mysql错误在单独的包中使用时拒绝使用go-sql-driver的用户访问

batch-file - bat文件中只获取没有 "IPv4 Address. . . . . . . . . . . :"的IPv4地址

python - 启动自己的终端工具作为命令的参数

go - 为什么追加覆盖子元素?

go - http.StripPrefix : Serving a file from a custom folder

linux - 每 2 :30 on every day? 运行一次 cron 作业

java - 为什么下面的代码不起作用?