2

I'm trying to check to see if a shell binary exists on the machine via Go.

I have tried some simpler shell based commands:

    args := []string{"-x", "fly"}
    o, err := exec.Command("test", args...).Output()
    fmt.Println(err)
    fmt.Println(o)

But this has an exit of 1 no matter what and outputs nothing.

I'm wondering if there is something in Go itself that would have this functionality as obviously I'd rather do the heavy lifting with go itself.

Thanks!

jaibhavaya
  • 108
  • 1
  • 7
  • @MiloChristiansen is this a possible duplicate or an exact duplicate? I think the question is not about checking a file like "/home/user/abc.txt", it is more likely to check if "telnet" works (in $PATH). (I do not know golang) – JCasso Oct 18 '17 at 22:39
  • I can't tell, do you want the equivalent of `test -x`, or do want some other behavior? – JimB Oct 19 '17 at 01:39
  • yea it was mostly checking to see if something like telnet works in the PATH. Checking for a file wasn't working as I would need to do extra work to find the full path to the executable. I was trying to see if there was something like -x in unix – jaibhavaya Oct 19 '17 at 18:54
  • 1
    @jaibhavaya: that's 2 different issues. There's [`exec.LookPath`](https://golang.org/pkg/os/exec/#LookPath), which looks for the file in your PATH, and that should be an executable so you don't need to test it, you just try to execute it. What `test -x` does is check if the file mode has any executable bits set (but that doesn't necessarily mean _you_ can execute it.). You have the mode bits via the [`FileInfo.Mode`](https://golang.org/pkg/os/#FileInfo) method. – JimB Oct 19 '17 at 21:12
  • I think @JimB's solution should be the answer (and this question shouldn't be a duplicate since the asker specifically states an executable, not just any file, for which Go has a specific solution) – atp Apr 12 '18 at 14:13
  • You can use `exec.LookPath`. This question is actually not a duplicate of "how to check if a file exists in Go". – caarlos0 Apr 27 '22 at 13:28

1 Answers1

4

Here is one way to simply check if a file exists.

if _, err := os.Stat("/dir/file"); os.IsNotExist(err) {
    fmt.Printf("File doesn't exist")
} else {
    fmt.Printf("Exists")
}

Find out more: os.Stat(), os.IsNotExist()

Nick Krasnov
  • 26,886
  • 6
  • 61
  • 78