Reverse id command, I want the User/Group Name from the uid or gid

10,212

Solution 1

You can use the getent command, which will perform the lookup based on /etc/nsswitch.conf. This means that if ldap is configured on the system, getent will attempt to lookup the user in ldap. Here is an example:

$ getent passwd 33
www-data:x:33:33:www-data:/var/www:/bin/sh

Solution 2

To get the username associated with a UID, use the -n option of id:

$ id
uid=1000(myself) gid=1000(myself) groups=1000(myself), 0(wheel), 9(wsrc)
$ id -n -u 1000
myself

This would not work on GIDs though as id expects usernames or UIDs:

$ id -n -g 9
id: 9: No such user

You can query both the passwd database and the group database for UIDs and GIDs with getent:

$ getent passwd 1000
myself:*:1000:1000:Just me,,,:/home/myself:/bin/sh
$ getent group 9
wsrc:*:9:myself

The actual username or group name may be parsed out of that by piping the output through cut -d : -f 1.


id is a POSIX utility, while getent is not.

Share:
10,212

Related videos on Youtube

Gregg Leventhal
Author by

Gregg Leventhal

Updated on September 18, 2022

Comments

  • Gregg Leventhal
    Gregg Leventhal almost 2 years

    I know some uid and gids that I don't know who they belong to and they are not in /etc/passwd (could be LDAP or from another system). How do I get Id info from only uid or gid preferably without using ldapsearch or any LDAP commands outside of getent or id, or something easy. Linux 2.6 Kernel, Red Hat variants.