user9614249
user9614249

Reputation:

How to get the full path of an executable in $PATH in Go

I would like have the functionality of which using Go.

I would like to get the full path of some program in $PATH, or nothing if the program is not in $PATH.

I checked in the os package but I don't see anything relevant to achieve this functionality.

My backup is exec.Command("which", "program") but that seems like overkill.

Upvotes: 2

Views: 3564

Answers (1)

Peter
Peter

Reputation: 31691

Use os/exec.LookPath:

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. The result may be an absolute path or a path relative to the current directory.

Use path/filepath.Abs if you need the path to be absolute in all cases:

package main

import (
    "log"
    "os/exec"
    "path/filepath"
)

func main() {
    fname, err := exec.LookPath("go")
    if err == nil {
        fname, err = filepath.Abs(fname)
    }
    if err != nil {
        log.Fatal(err)
    }

    log.Println(fname)
}

Upvotes: 6

Related Questions