dpl74687
dpl74687
2019-08-30 17:33

Nginx版本命令不返回版本也不错误

  • command
已采纳

I'm trying to check which version of Nginx is installed on my computer using Go.

This is my snippet:

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
}

For Go and Firefox it works perfectly fine, however for Nginx it returns neither a version nor an error. It seems to return an empty string...

Looking at the permissions: Firefox file is a symlink to a sh file owned by root:root with permissions 755. Nginx file is owned by root:root with permissions 755 as well.

Of course, running the command nginx -v works.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanqin2026 duanqin2026 2年前

    You're expecting the output from stdout. It is printing to stderr. Try cmd.CombinedOutput()

    点赞 评论 复制链接分享

为你推荐