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

前端 未结 10 1414
旧时难觅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

    On a modern glibc system, use this command:

    getent passwd "username" | cut -d ':' -f 5
    

    That'll get you the passwd entry of the specified user, independent of the underlying NSS module.

    Read the manpage of getent.


    If you're already programming, you can use the getpwnam() C-Function:

    struct passwd *getpwnam(const char *name);
    

    The passwd struct has a pw_gecos member which should contain the full name of the user.

    Read the manpage of getpwnam().


    Be aware that many systems use this field for more than the full name of the user. The most common convention is to use a comma (,) as separator within the field and place the users real name first.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-31 09:00

    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.

    0 讨论(0)
  • 2021-01-31 09:04

    The way that I figured it on Linux to get the full name into a variable was:

    u_id=`id -u`
    uname=`awk -F: -vid=$u_id '{if ($3 == id) print $5}' /etc/passwd`
    

    Then just simple use the variable, ex: $ echo $uname

    0 讨论(0)
提交回复
热议问题