I am trying to run a simple golang code
$ cat blah.go
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("sudo","ls")
out, err := cmd.Output()
fmt.Printf("%s", string(out))
fmt.Printf("%s", err.Error())
}
I am getting:
$ go run blah.go
blah.go
utils.go
weave_help_test.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x20 pc=0x400dc1]
goroutine 1 [running]:
runtime.panic(0x4b32a0, 0x5b1fc8)
/usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.main()
/home/Abhishek/go/src/github.com/blah.go:12 +0x1c1
exit status 2
How should I debug it?
$ go version
go version go1.2.1 linux/amd64
the error object returned from the running the command is nil (which is good! that means it succeeded!). But you are accessing err.Error() which on a nil object would result in just that panic.
So
a. check if err is nil
b. you can just print it, no need to call err.Error()
i.e. your code should look like this:
out, err := cmd.Output()
if err != nil {
fmt.Println("Error running command:", err)
return
//or even panic here
}
// we only get here if err is nil
fmt.Printf("%s", string(out))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With