3

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
2
  • 1
    You should check error returned by cmd.Output before using its result. Commented Feb 26, 2015 at 5:53
  • Thanks, works after the error check! Commented Feb 26, 2015 at 6:34

1 Answer 1

5

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining. Rookie mistake on my part :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.