How do I get the name of the active user via the command line in OS X?
as 'whoami' has been obsoleted, it's probably more forward compatible to use:
id -un
There are two ways-
whoami
or
echo $USER
whoami
EDIT
The whoami utility has been obsoleted by the id(1) utility, and is equivalent to id -un
. The command id -p
is suggested for normal interactive use.
The question has not been completely answered, IMHO. I will try to explain: I have a crontab entry that schedules a bash shell command procedure, that in turn does some cleanup of my files; and, when done, sends a notification to me using the OS X notification center (with the command osascript -e 'display notification ...
). If someone (e.g. my wife or my daughter) switches the current user of the computer to her, leaving me in the background, the cron script fails when sending the notification.
So, Who is the current user means Has some other people become the effective user leaving me in the background? Do stat -f "%Su" /dev/console
returns the current active user name?
The answer is yes; so, now my crontab shell script has been modified in the following way:
...
if [ "$(/usr/bin/stat -f ""%Su"" /dev/console)" = "loreti" ]
then /usr/bin/osascript -e \
'display notification "Cleanup done" sound name "sosumi" with title "myCleanup"'
fi
getting username in MAC terminal is easy...
I generally use whoami
in terminal...
For example, in this case, I needed that to install Tomcat Server...
You can also retrieve it from the environment variables, but that is probably not secure, so I would go with Andrew's answer.
printenv USER
If you need to retrieve it from an app, like Node, it's easier to get it from the environment variables, such as
process.env.USER
.