Many scripted macOS workflows require determining the username of the currently logged-in user. Whether you wish to execute a command as that user via
su or you just want to log the username during your script’s execution, you may need to query macOS for this information.
This is a solved problem, and Armin Briegel’s excellent article on Getting the current user in macOS outlines the best method.
In addition to determining the logged-in user’s username, you may also need their user ID number, or UID. For example, loading a LaunchAgent as a specific user requires providing that user’s UID.
Previous solutions involved grabbing the logged-in user’s username, then feeding that to
id -u $loggedInUser – but you can get the currently logged-in user’s UID in one step.