Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the logged in user's real name in Unix?

Tags:

unix

I'm looking to find out the logged in user's real (full name) to avoid having to prompt them for it in an app I'm building. I see the finger command will output a columned list of data that includes this and was wondering if it makes sense to grep through this or is there an easier way? None of the switches for finger that I've found output just the real name. Any thoughts would be much appreciated.

like image 269
braitsch Avatar asked Jul 08 '11 02:07

braitsch


People also ask

How do I print a Unix login name?

How do I find out the current login name on Linux or Unix-like operating system using command prompt? You can display or print the name of the current user (also know as calling user) using logname command. This command reads var/run/utmp or /etc/utmp file to display the name of the current user.

How do I find the full username in Linux?

The full names are stored in /etc/passwd . On the command line you can change it using the command chfn (needs sudo if you want to change other user's names).

How can I find user name?

In the box, type cmd and press Enter. The command prompt window will appear. Type whoami and press Enter. Your current user name will be displayed.


3 Answers

getent passwd `whoami` | cut -d : -f 5

(getent is usually preferable to grepping /etc/passwd).

like image 106
Todd Owen Avatar answered Nov 12 '22 04:11

Todd Owen


getent passwd "$USER" | cut -d: -f5 | cut -d, -f1

This first fetches the current user's line from the passwd database (which might also be stored on NIS or LDAP)

In the fetched line, fields are separated by : delimiters. The GECOS entry is the 5th field, thus the first cut extracts that.

The GECOS entry itself is possibly composed of multiple items - separated by , - of which the full name is the first item. That's what the second cut extracts. This also works if the GECOS entry is lacking the commas. In that case the whole entry is the first item.

You can also assign the result to a variable:

fullname=$( getent passwd "$USER" | cut -d: -f5 | cut -d, -f1 )

Or process it further directly:

echo "$( getent passwd "$USER" | cut -d: -f5 | cut -d, -f1 )'s home is $HOME."
cat <<EOF
Hello, $( getent passwd "$USER" | cut -d: -f5 | cut -d, -f1 ).
How are you doing?
EOF
like image 26
blubberdiblub Avatar answered Nov 12 '22 06:11

blubberdiblub


You can use getpwent() to get each successive password entry until you find the one that matches the currently logged in user, then parse the gecos field.

Better, you can use getpwuid() to directly get the entry for the uid of the current user.

In either case,

  1. You have to first get the current user's login name or id, and
  2. There is no guarantee that the gecos field actually contains the user's real full name, or anything at all.
like image 45
Stephen P Avatar answered Nov 12 '22 04:11

Stephen P