Exercise in determining from whence we came.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.0 KiB

9 years ago
9 years ago
9 years ago
9 years ago
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "os/exec"
  7. "path"
  8. "strings"
  9. "github.com/kardianos/osext"
  10. )
  11. func main() {
  12. // Find location of executable with kardianos/osext
  13. exeFolder, err := osext.ExecutableFolder()
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. //
  18. // These will require that the executable is in a directory within the $PATH
  19. // Find location of executable with Args[0] and exec.LookPath
  20. // Requires import of os, os/exec, and path
  21. argZero := os.Args[0]
  22. exePath, err := exec.LookPath(argZero)
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. lookPath := path.Dir(exePath)
  27. // Walk the path environment locally
  28. walkPath := pathWalker(os.Args[0])
  29. // Output to comapre the results
  30. fmt.Printf("osext.ExeFolder : %s\n", exeFolder)
  31. fmt.Printf("exec.LookPath : %s\n", lookPath)
  32. fmt.Printf("local walkPath : %s\n", walkPath)
  33. }
  34. func pathWalker(file string) string {
  35. path := os.Getenv("PATH")
  36. for _, dir := range strings.Split(path, ":") {
  37. exe := dir + "/" + file
  38. if _, err := os.Stat(exe); err == nil {
  39. return dir
  40. }
  41. }
  42. return "not found"
  43. }