Skip to content

Instantly share code, notes, and snippets.

@arbal
Created January 8, 2023 22:31
Show Gist options
  • Select an option

  • Save arbal/5e2ec6100d23c980f19bb9d17fb3b952 to your computer and use it in GitHub Desktop.

Select an option

Save arbal/5e2ec6100d23c980f19bb9d17fb3b952 to your computer and use it in GitHub Desktop.
Ways to get the current/active GUI (Console) user in macOS

Grab the current or most recent console user in macOS

Should work on Linux as well.

id -un

stat returns last user logged in most recently.

stat -f %Su /dev/console

Can cause some false positives depending on environment.

ls /dev/console | awk '{ print $3 }'

Using scutil

$( scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }' )

The "preferred" way to get the current console user in Mac.

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");')

With launchctl

When running launchctl asuser you will need the UID.

launchctl asuser $(id -u $(stat -f%Su /dev/console))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment