PaulW
PaulW

Reputation: 29

Bash Script - get User Name given UID

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.

Upvotes: 1

Views: 4065

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98871

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/

Upvotes: 2

Ged
Ged

Reputation: 301

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

Upvotes: 3

Related Questions