How - given USER ID as parameter, find out what is his name? The problem is to write a Bash script, and somehow use etc/passwd file.
Asked
Active
Viewed 3,453 times
1
-
1What did you try? did you make an effort to solve this? – Inian Dec 18 '16 at 13:38
-
And which Linux distro are you in/ – Inian Dec 18 '16 at 13:47
-
Im using Ubuntu. I thought about using cat, to get everything that is inside etc/passwd, but I dont know what do next – PaulW Dec 18 '16 at 14:07
-
1Can you try `getent passwd "
" | cut -d: -f1` to see if it works? – Inian Dec 18 '16 at 14:09 -
It does not output anything. Shouldnt I use IFS, to specify somehow to treat ':' as a separator? – PaulW Dec 18 '16 at 14:10
-
The cut `-d:` is meant for that, can you let me know if `getent passwd "
"` if it is properly printing the values? – Inian Dec 18 '16 at 14:11
2 Answers
3
The uid
is the 3rd field in /etc/passwd
, based on that, you can use:
awk -v val=$1 -F ":" '$3==val{print $1}' /etc/passwd
4 ways to achieve what you need:
http://www.digitalinternals.com/unix/linux-get-username-from-uid/475/

Pedro Lobito
- 94,083
- 31
- 258
- 268
2
Try this:
grep ":$1:" /etc/passwd | cut -f 1 -d ":"
This greps for the UID within /etc/passwd.
Alternatively you can use the getent command:
getent passwd "$1" | cut -f 1 -d ":"
It then does a cut and takes the first field, delimited by a colon. This first field is the username.
You might find the SS64 pages for cut and grep useful: http://ss64.com/bash/grep.html http://ss64.com/bash/cut.html

Ged
- 181
- 1
- 7
-
1I believe that the first solution may sometimes give wrong results if the primary gid parameter for some other user if equal to the uid you are searching for. – Liberat0r Oct 19 '18 at 14:02
-
commentor above is correct. If you want to use grep, you should instead do `grep -E "${1}:[0-9]+::"` – Ajax Jul 18 '22 at 23:06