开发者

How to get the logged in user's real name in 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 ou开发者_如何学运维tput just the real name. Any thoughts would be much appreciated.


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

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


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


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.


Specific to macOS, there is no getent command; instead you have to use id -F


For macOS and Linux:

if [ "Darwin" = $(uname) ]; then FULLNAME=$(id -P $USER | awk -F '[:]' '{print $8}') else FULLNAME=$(getent passwd $USER | cut -d: -f5 | cut -d, -f1) fi echo $FULLNAME


I use

grep "^$USER:" /etc/passwd | awk -F: '{print $5}'

Explanations:

  • $USER contains the login of the current user
  • The first part (grep) extract from /etc/passwd the line about that user
  • The second part (awk) splits this line with separator ':' and prints the 5th component, which is the full name

If you don't want to rely on $USER being set, you can use that instead:

grep "^`whoami`:" /etc/passwd | awk -F: '{print $5}'


How about trying whoami or logname

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜