-
Notifications
You must be signed in to change notification settings - Fork 3
/
shell_posix.go
60 lines (50 loc) · 1.34 KB
/
shell_posix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//go:build !darwin && !plan9 && unix
package shell
import (
"bufio"
"os"
"os/exec"
"os/user"
"strings"
)
// CurrentUserShell returns the current user's shell.
func CurrentUserShell() (string, bool) {
// If the SHELL environment variable is set, use it.
if shell, ok := os.LookupEnv("SHELL"); ok {
return shell, true
}
// Try to get the current user. If we can't then fallback to the default
// shell.
u, err := user.Current()
if err != nil {
return DefaultShell(), false
}
// If getpwnam_r is available, use it.
if shell, ok := cgoGetUserShell(u.Username); ok {
return shell, true
}
// If getent is available, use it.
if getent, err := exec.LookPath("getent"); err == nil {
if output, err := exec.Command(getent, "passwd", u.Username).Output(); err == nil {
if fields := strings.SplitN(strings.TrimSuffix(string(output), "\n"), ":", 7); len(
fields,
) == 7 {
return fields[6], true
}
}
}
// If the user has an entry in /etc/passwd, use it.
if f, err := os.Open("/etc/passwd"); err == nil {
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
fields := strings.SplitN(strings.TrimSuffix(s.Text(), "\n"), ":", 7)
if len(fields) == 7 && fields[0] == u.Username {
return fields[6], true
}
}
_ = s.Err() // Ignore errors.
}
// Fallback to the default shell.
return DefaultShell(), false
}