I have a method to quickly run a shell command:
func runcmd(c string, arg ...string) (string, string, string) {
var o bytes.Buffer
var e bytes.Buffer
cmd := exec.Command(c, arg...)
cmd.Stdout = &o
cmd.Stderr = &e
err := cmd.Run()
return o.String(), e.String(), err.Error()
}
In my main have the following code:
func main() {
ver, _, exitcode := runcmd("rpm", "-q", "--queryformat", "%{VERSION}", "redhat-release")
var dist string
if exitcode != "" {
ver, _, exitcode = runcmd("rpm", "-q", "--queryformat", "%{VERSION}", "centos-release")
if exitcode != "" {
fmt.Println("Unknown OS! Exiting without running!")
os.Exit(3)
}
dist = "CentOS"
} else {
dist = "Redhat/Redhat derivative"
}
fmt.Printf("System is %s %s.
", dist, ver)
}
Running this produces a SIGSEGV. However, when I comment the second call to runcmd
it runs as normal (returning Unknown OS! Exiting without running! exit status 3
). I'm new to go so i don't really understand the nil pointer dereference error to begin with, much less why it would only happen on the second call.