How do I get the name of the active user via the c

2020-02-07 18:53发布

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

12条回答
Anthone
2楼-- · 2020-02-07 18:57

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
查看更多
狗以群分
3楼-- · 2020-02-07 18:58

You can also use the logname command from the BSD General Commands Manual under Linux or MacOS to see the username of the user currently logged in, even if the user is performing a sudo operation. This is useful, for instance, when modifying a user's crontab while installing a system-wide package with sudo: crontab -u $(logname)

Per man logname:

LOGNAME(1)

NAME
    logname -- display user's login name
查看更多
We Are One
4楼-- · 2020-02-07 19:01

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.

查看更多
虎瘦雄心在
5楼-- · 2020-02-07 19:01

Via here

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

stat -f "%Su" /dev/console

查看更多
来,给爷笑一个
6楼-- · 2020-02-07 19:04

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

id -un
查看更多
Animai°情兽
7楼-- · 2020-02-07 19:07

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.

查看更多
登录 后发表回答