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

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

提交回复
热议问题