How can I obtain the Full Name of the currently logged in user via Terminal when run as root?

Simply use id -P $(stat -f%Su /dev/console) | awk -F '[:]' '{print $8}'

id -P $(stat -f%Su /dev/console) yields:

adminuser:********:501:20::0:0:AdminUser:/Users/adminuser:/bin/bash

awk -F '[:]' '{print $8}' yields the 8th term (the "RealName") of an output separated by colons.

As proposed by fd0 you can alternatively use:

id -P $(stat -f%Su /dev/console) | cut -d : -f 8

which is even more simple/elegant.


You can use dscl to read the RealName:

$ dscl . -read /Users/grgarside RealName
RealName:
 George Garside

The following will give you just what you're after. This uses ‘who am i’ to get the username, then sed to format the output.

$ dscl . -read "/Users/$(who am i | awk '{print $1}')" RealName | sed -n 's/^ //g;2p'
George Garside

Needed a two-line approach:

username="$(stat -f%Su /dev/console)"
realname="$(dscl . -read /Users/$username RealName | cut -d: -f2 | sed -e 's/^[ \t]*//' | grep -v "^$")"

And then you can just echo out the realname variable.