NOTE: Due to macOS Monterey's prompts when Python 2 in invoked, please review the blog post here to get the logged in user instead.

When running scripts via Jamf Pro, Munki or a launch daemon, you sometimes have a challenge to get the username of the currently logged in user.
Below has a method to achieve this, with a link to an Apple approved method.
The challenge
If you’re running a script via Jamf Pro at login or via Self Service, then $3 can be used to grab the username.
However, what if you need to check at another time or you don’t have Self Service?
A common method used is below & you’ll find it in a number of my scripts.
loggedInUser=$(/bin/ls -l /dev/console | /usr/bin/awk '{ print $3 }')
The recommendation
On seeing an example of the above, Frogor over at the ##OSX-Server IRC mentioned that this method was both a little “odd” & not Apple’s recommended way. Then, being the guy he is.. He not only pointed us in IRC to a link about Apple’s recommended method, but also gave an example of how to call it within bash. That example is below:
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");')
You’ll start to see the above soon in my new posts, & if you do use Fast User Switching then this may work better for you where other methods have failed.