Golang gets nginx version

I use go"s exec.command to execute / usr/local/nginx/sbin/nginx-v command to get version information. I can"t get any returned results. If I execute redis-v mysql-v and so on, I can get the correct results. And I have no problem with manually executing nginx-v on the terminal. What is the reason for this? Or is there any other way to get it?

cmd := exec.Command("/usr/local/nginx/sbin/nginx", "-v")
cmd.SysProcAttr = &syscall.SysProcAttr{
    Setpgid:true,
}
stdout, err := cmd.StdoutPipe()
if err != nil {
    //log.Fatal(err)
    fmt.Println(err)
}
// 
defer stdout.Close()
// 
if err := cmd.Start(); err != nil {
    fmt.Println(err)
}
// 
opBytes, err := ioutil.ReadAll(stdout)
if err != nil {
    fmt.Println(err)
}
if err := cmd.Wait(); err != nil {
    fmt.Println(err)
}
return string(opBytes)
Mar.12,2021

nginx-v writes data to stderr , so you can't get data from stdout . Can be verified in the shell environment, nginx-v 2 >. / version.txt .

With

knowing this, it's easy to get this information through exec.Command .

cmd := exec.Command("nginx", "-v")
cmd.SysProcAttr = &syscall.SysProcAttr{
    Setpgid: true,
}

out, err := cmd.CombinedOutput()
if err != nil {
    fmt.Fprintln(os.Stderr, err)
}
fmt.Println(string(out))

nginx-v Why not write data to stdout ? It's really weird

Menu