Skip to content

Instantly share code, notes, and snippets.

@StephenBrown2
Created May 11, 2021 16:27
Show Gist options
  • Save StephenBrown2/380027f23e6d9788326e977699059f9b to your computer and use it in GitHub Desktop.
Save StephenBrown2/380027f23e6d9788326e977699059f9b to your computer and use it in GitHub Desktop.
Find items that exist in multiple places in the os PATH
package main
import (
"fmt"
"os"
"sort"
"strings"
)
func main() {
dirs := strings.Split(os.Getenv("PATH"), ":")
if len(dirs) == 1 && dirs[0] == "" {
fmt.Println("No paths found! is 'PATH' var populated?")
os.Exit(1)
}
fmt.Printf("Searching paths: %+v\n\n", dirs)
maxLen := 0
bins := []string{}
paths := map[string][]string{}
for _, p := range dirs {
if len(p) == 0 {
continue
}
files, err := os.ReadDir(p)
if err != nil {
fmt.Println(err)
continue
}
for _, file := range files {
name := file.Name()
if file.IsDir() {
name = name + " (dir)"
}
if len(name) > maxLen {
maxLen = len(name)
}
if _, ok := paths[name]; !ok {
bins = append(bins, name)
}
paths[name] = append(paths[name], p)
}
}
fmt.Println()
sort.Strings(bins)
for _, bin := range bins {
if len(paths[bin]) > 1 {
fmt.Printf("%*s found in multiple locations: %s\n", maxLen, bin, paths[bin])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment