id -un
stat -f %Su /dev/console
ls /dev/console | awk '{ print $3 }'
$( scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }' )
This method supports environments where fast-user switching is enabled.
References: Apple Developer, MacMule
Runnung Sierra 10.12.5 I had to modify to explicitly call /usr/bin/python otherwise I recieve the following:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named SystemConfiguration
loggedInUser=$(/usr/bin/python -c 'from SystemConfiguration import SCDynamicStoreCopyConsoleUser; import sys; \
username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0]; username = [username,""][username in [u"loginwindow", None, u""]]; \
sys.stdout.write(username + "\n");')
When running launchctl asuser you will need the UID.
launchctl asuser $(id -u $(stat -f%Su /dev/console))