MacOS – Identifying an accounts username upon login

macos

I am trying to run a launch agent upon a user logging in, but the script encapsulated by it requires knowing who is logging in. Previously I could identify the user logging in by checking the owner of /dev/console but this no longer works. The owner of /dev/console is root upon a user's login or more precisely when the launch agent runs as it changes to the user afterwards. Is there anywhere I can find out the username of a person logging in for the purposes of a launch agent?

Best Answer

CurrentUser="$(env | grep LOGNAME | awk -F = '{print $2}')" and $USER used in a script launched by a launch agent in /Library/LaunchAgents both contain the username of the user logging in.

CurrentUser="$(users)" contains all users. So the first user will be revealed but logging in with a second user at the same time (e.g. fast user switching) will break the script.