Linux: Get Username from UID

Objective: To get a user’s username given his id or UID.

To get the username from the /etc/passwd file, we will need to match the UID with the 3rd field in the passwd file. So, to check for a user with an UID of 1000, we can use the following syntax.

$ awk -v uid=1000 -F":" '{ if($3==uid){print $1} }' /etc/passwd
ibrahim

To print the whole line from the passwd file once a match is found, use the following syntax.

$ awk -v uid=1000 -F":" '{ if($3==uid){print $0} }' /etc/passwd
ibrahim:x:1000:50::/home/ibrahim:/bin/bash

The optmised way (based on user comment) to print the whole line is by using the following awk syntax.

$ awk -v uid=1000 -F: '$3 == uid' /etc/passwd
ibrahim:x:1000:50::/home/ibrahim:/bin/bash

The above method is only applicable if it’s a local user. If the name service switch configuration file, nsswitch.conf, is configured to use NIS for user accounts, then the user information might not be available in the /etc/passwd file. In such cases, use the getent utility to map the UID to username.

$ getent passwd 1000
ibrahim:x:1000:50::/home/ibrahim:/bin/bash

The getent utility will displays entries from databases supported by the Name Service Switch libraries, which are configured in /etc/nsswitch.conf. So, it is able to search for local accounts stored in the /etc/passwd file as well.

Update (12-July-2015): Added an optmised way of printing whole line using awk based on user comment.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }