What's the easiest way to get a user's ful

2019-03-09 00:39发布

I could grep through /etc/passwd but that seems onerous. 'finger' isn't installed and I'd like to avoid that dependency. This is for a program so it would be nice if there was some command that let you just access user info.

10条回答
太酷不给撩
2楼-- · 2019-03-09 00:57

Take 1:

$ user_name=sshd
$ awk -F: "\$1 == \"$user_name\" { print \$5 }" /etc/passwd
Secure Shell Daemon

However, passwd database supports special character '&' in the gecos, which should replaced with capitalized value of user name:

$ user_name=operator
$ awk -F: "\$1 == \"$user_name\" { print \$5 }" /etc/passwd
System &

Most of answers here (except for finger solution) do not respect &. If you want to support this case, then you'll need a more complicated script.

Take 2:

$ user_name=operator
$ awk -F: "\$1 == \"$user_name\" { u=\$1; sub(/./, toupper(substr(u,1,1)), u);
    gsub(/&/, u, \$5); print \$5 }" /etc/passwd
System Operator
查看更多
三岁会撩人
3楼-- · 2019-03-09 00:59

My code works in bash and ksh, but not dash or old Bourne shell. It reads the other fields too, in case you might want them.

IFS=: read user x uid gid gecos hm sh < <( getent passwd $USER )
name=${gecos%%,*}
echo "$name"

You could also scan the whole /etc/passwd file. This works in plain Bourne shell, in 1 process, but not so much with LDAP or what.

while IFS=: read user x uid gid gecos hm sh; do
  name=${gecos%%,*}
  [ $uid -ge 1000 -a $uid -lt 60000 ] && echo "$name"
done < /etc/passwd

On the other hand, using tools is good. And C is good too.

查看更多
爷的心禁止访问
4楼-- · 2019-03-09 01:02

The good old finger may also help :-)

finger $USER |head -n1 |cut -d : -f3
查看更多
迷人小祖宗
5楼-- · 2019-03-09 01:09

Combination of other answers, tested on minimal Debian/Ubuntu installations:

getent passwd `whoami` | cut -d ':' -f 5 | cut -d ',' -f 1
查看更多
登录 后发表回答