I'm using the Packages app to create an installer which includes, among other things, a launchd job.

The postinstall Bash script needs to target the logged in user as follows:

launchctl bootstrap gui/$UID ~/Library/LaunchAgents/com.mycompany.myproduct.plist

The problem is that $UID returns 0 when run from within the package.

The following tweak works as expected on my machine but the target deployment users don't use 501 but mobile accounts so the UID differs with each AD account

launchctl bootstrap gui/501 ~/Library/LaunchAgents/com.mycompany.myproduct.plist

I've tried all sorts of things:

$(who -m | awk '{print $1;})
$(logname 2>/dev/null || $SUDO_NAME)

All return the 0/root user.

This seems to work, on my machine, when run it Terminal after sudo su. But, as I don't understand the /dev/console bit (or the %Su parameter), is it 100% reliable?

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

1 Answer 1


The stat command is run with the -f%Su parameter, where -f means that an output format follows, and %Su means that it should output (%) a string (S) which is the user ID (u) of the file's owner.

Your command then provides the username to the id command in order to get to the username - which seems to be a way roundabout way of getting that, as you could just have asked stat for it initially like this:

stat -f%Uu /dev/console

Doing it like this means you won't have to call id and cut.

The stat command is completely reliable in returning the user id/name of the owner of the /dev/console file (or actually character device). The question is just whether this user is the one, you're looking for. In general, it will work - but you might see a different behaviour than you're expecting when users are also logged in via Remote Desktop. In that case, the last login performed will be returned (i.e. when multiple user's are logged in at the same time).

There's also a different method of getting the currently logged in user by asking the System Configuration Daemon:

scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }'

The difference between the two is that looking at /dev/console cannot distinguish between root being logged in (i.e. root logins have been enabled by the user), or the computer being sat at the login window - both will return root as the owner of the file. Whether or not this is a problem for you depends on your specific use-case.

  • Super answer @jkseogaard thank you. Returning to man stat with your answer as a reference also helped me decode what I'd already read! (% is rather hidden). This PKG will probably be deployed by Jamf so I'm really not sure if /dev/console will work reliably but I'm about to find out! Commented May 19, 2021 at 21:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .