How can I return the logged in user from inside a pkg which is running as root? 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:
$SUDO_USER
$LOGNAME
$(who -m | awk '{print $1;})
$(logname 2&gt;/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
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 &lt;&lt;&lt; &quot;show State:/Users/ConsoleUser&quot; | awk '/Name :/ &amp;&amp; ! /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.