Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a user's friendly username on UNIX?

Tags:

bash

unix

I want to get the "friendly" name, not the username, at least if such a string exists for the given user. Things I've tried:

whoami
jamesarosen

id -un
jamesarosen

id -p
uid jamesarosen
groups  staff com.apple.access_screensharing ...

id -P
jamesarosen:********:501:20::0:0:James A. Rosen:/Users/jamesarosen:/bin/bash

That last one has the information I'm looking for, but I'd prefer not to have to parse it out, particularly since I'm not terribly confident that the format (specifically the number of :s) will remain consistent across OSes.

like image 310
James A. Rosen Avatar asked Nov 05 '12 23:11

James A. Rosen


3 Answers

Parse the GECOS Field for User's Full Name

The format of /etc/passwd and most of the GECOS field is extremely well standardized across Unix-like systems. If you find an exception, by all means let us know. Meanwhile, the easiest way to get what you want on a Unix-like system is to use getent and cut to parse the GECOS field. For example:

getent passwd $LOGNAME | cut -d: -f5 | cut -d, -f1
like image 200
Todd A. Jacobs Avatar answered Sep 26 '22 04:09

Todd A. Jacobs


The only way that I know would be to parse it:

grep -P "^$(whoami):" /etc/passwd | cut -f5 -d:

You can be pretty certain of the format of /etc/passwd

like image 32
cEz Avatar answered Sep 25 '22 04:09

cEz


You could use finger to obtain that information:

finger `id -un` | head -1 | cut -d: -f3-

which has the advantage (or disadvantage, depending on your requirements) that it will retrieve the information for non-local users as well.

If you only want to get the information from /etc/passwd, you'll most likely have to parse the file one way or the other, as others have already mentioned. Personally I'd prefer awk for this task:

awk -F: -vid=`id -u` '{if ($3 == id) print $5}' /etc/passwd
like image 33
Ansgar Wiechers Avatar answered Sep 24 '22 04:09

Ansgar Wiechers