简体   繁体   中英

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM