What's the easiest way to get a user's full name on a Linux/POSIX system?

前端 未结 10 1412
旧时难觅i
旧时难觅i 2021-01-31 08:29

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

10条回答
  •  执笔经年
    2021-01-31 08: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
    

提交回复
热议问题