views:

132

answers:

7

How do I get the name of the active user via the command line in OS X?

A: 

Via here

Checking the owner of /dev/console seems to work well.

stat -f "%Su" /dev/console

Lawrence Johnston
+3  A: 

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.

dfa
+1  A: 

I'm pretty sure the terminal in OS X is just like unix, so the command would be:

whoami

I don't have a mac on me at the moment so someone correct me if I'm wrong.

Eric Koslow
yes, OSX 10.5 is (finally) a fully qualified Unix.
kent
A: 

I don't have a mac here neither, but I'd bet there's also a $USER environment variable.

fortran
But an environment variable is utterly unreliable - I have both $USER and $LOGNAME set, but that's because I chose to ensure that both are set (to the value of my choosing). It may not matter - we don't have enough context in the question to tell how much the security and reliability matters.
Jonathan Leffler
+5  A: 

as 'whoami' has been obsoleted, it's probably more forward compatible to use:

id -un
kent
In what sense is 'whoami' obsoleted? Who has declared it obsolete?
Jonathan Leffler
type 'man whoami'
kent
@Jonathan: The man page for `whoami` on Leopard confirms that it has been replaced by `id`.
Naaff
Agh! Why are they changing something that has been around since the dawn of time?
dmckee
A: 

Define 'active user'.

If the question is 'who is the logged in user', then 'who am i' or 'whoami' is fine (though they give different answers - 'whoami' reports just a user name; 'who am i' reports on terminal and login time too).

If the question is 'which user ID is the effective ID for the shell', then it is often better to use 'id'. This reports on the real and effective user ID and group ID, and on the supplementary group IDs too. This might matter if the shell is running SUID or SGID.

Jonathan Leffler
A: 

If you want to know who's currently logged in to the system:

$ w
 15:56:14 up 5 days, 20:58,  6 users,  load average: 0.43, 0.53, 0.50
USER     TTY        LOGIN@   IDLE   JCPU   PCPU WHAT
me       pts/2     Fri19    1:03m  0.98s  0.98s -/bin/bash
me       pts/3     09:55    6:00m  0.43s  0.43s /bin/bash
me       pts/5     15:56    0.00s  0.23s  0.00s w

(This is from a Linux system; the formatting on OS X may be slightly different, but the information should be about the same.)

There may be multiple login sessions; UNIX is designed to be a multi-user system, after all.

ephemient