Update "dirUnix" to use "getent" and only fallback to shell if that fails
diff --git a/homedir.go b/homedir.go
index ed920de..6944957 100644
--- a/homedir.go
+++ b/homedir.go
@@ -7,6 +7,7 @@
"os/exec"
"path/filepath"
"runtime"
+ "strconv"
"strings"
"sync"
)
@@ -81,9 +82,28 @@
return home, nil
}
- // If that fails, try the shell
+ // If that fails, try getent
var stdout bytes.Buffer
- cmd := exec.Command("sh", "-c", "eval echo ~$USER")
+ cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
+ cmd.Stdout = &stdout
+ if err := cmd.Run(); err != nil {
+ // If "getent" is missing, ignore it
+ if err != exec.ErrNotFound {
+ return "", err
+ }
+ } else {
+ if passwd := strings.TrimSpace(stdout.String()); passwd != "" {
+ // username:password:uid:gid:gecos:home:shell
+ passwdParts := strings.SplitN(passwd, ":", 7)
+ if len(passwdParts) > 5 {
+ return passwdParts[5], nil
+ }
+ }
+ }
+
+ // If all else fails, try the shell
+ stdout.Reset()
+ cmd = exec.Command("sh", "-c", "cd && pwd")
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return "", err