Method: LinuxStat::User.get_user
- Defined in:
- lib/linux_stat/user.rb
.get_user ⇒ Object Also known as: get_current_user
Returns the user ID as integer
It directly calls LinuxStat::Sysconf.get_uid and LinuxStat::Sysconf.get_gid
and then reads /etc/passwd and matches the values with UID and GID.
It doesn’t get affected with the assignment of USER environment variable
If either /etc/passwd is readable or LinuxStat::Sysconf.get_login() is not empty.
But if /etc/passwd isn’t readable (which is weird), it will fall back to sysconf.h’s get_login() If that’s not available, like in docker, falls back to ENV.to_s
It should return the username under most robust circumstances. But if nothing is available for some reason, it will return an empty String.
Note that this is not cached or memoized so use this at your own processing expense.
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/linux_stat/user.rb', line 101 def get_user unless passwd_readable? _l = LinuxStat::Sysconf.get_login().freeze return _l.empty? ? ENV['USER'.freeze].to_s : _l end uid, gid = LinuxStat::Sysconf.get_uid, LinuxStat::Sysconf.get_gid username = ''.freeze passwd.each { |x| splitted = x.split(?:).freeze if splitted[2].to_i == uid && splitted[3].to_i == gid username = splitted[0] break end } username end |