Debian Codegraph @

shell_posix.go

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