1

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.

PaulW
  • 29
  • 1
  • 6

2 Answers2

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
  • 1
    I 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