diff --git a/README.md b/README.md index 2691a3a..97f701a 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,12 @@ Examples of methods for determining the directory path where our executable resides. -- The `kardianos/osext` package is used for reference. The other methods will - require that the executable is located within the OS search path. +- The `github.com/kardianos/osext` package is used for reference. The other methods + will require that the executable is located within the OS search path. - The first alternative utilizes `exec.LookPath` to find the executable within the - OS search path. + OS search path. This method depends on the `os`, `os/exec`, and `path` packages. + +- The next method defines a local function to look for the file named in `args[0]` + in the directories listed in the `PATH` environment variable. This method depends + on the `os` and `strings` packages. diff --git a/main.go b/main.go index fa2695c..24e2f7f 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path" + "strings" "github.com/kardianos/osext" ) @@ -29,7 +30,22 @@ func main() { } lookPath := path.Dir(exePath) + // Walk the path environment locally + walkPath := pathWalker(os.Args[0]) + // Output to comapre the results fmt.Printf("osext.ExeFolder : %s\n", exeFolder) fmt.Printf("exec.LookPath : %s\n", lookPath) + fmt.Printf("local walkPath : %s\n", walkPath) +} + +func pathWalker(file string) string { + path := os.Getenv("PATH") + for _, dir := range strings.Split(path, ":") { + exe := dir + "/" + file + if _, err := os.Stat(exe); err == nil { + return dir + } + } + return "not found" }