Bash Script - get User Name given UID

3.7k views Asked by At

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.

2

There are 2 answers

0
Pedro Lobito On

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/

2
Ged On

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