Run a Command as the Logged-In User From a Root Mac Script
Root MDM script needs to act as the Mac user? Find the console user with stat, then run launchctl asuser with sudo -u, with a read-back and a backup.

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.
Mac MDM agents usually run scripts as root, so a plain command in that script acts as root, not as the person at the desk. To act as that person, read the console user’s name with stat -f %Su /dev/console and stop if the answer is root or empty. Then look up their UID with id -u and run the command through launchctl asuser "$uid" sudo -u "$user".
Both halves are needed. launchctl asuser moves the command into the user’s launchd context but leaves it running as root. sudo -u changes the user but leaves the command in root’s context. Use the pair for one-off commands while someone is signed in. Recurring or login-time work belongs in a LaunchAgent.
#How the usual workaround goes wrong
The common first attempt is sudo -u jsmith somecommand inside the root script. On a traditional Unix system that is enough, because switching the UID switches nearly everything that matters. macOS is different. A process also carries a Mach bootstrap namespace and a security audit session, and switching the UID leaves both behind.
A daemon running with the console user’s UID is not the same as an application that user launched. The command runs with the right UID in the wrong session. Anything that talks to the user’s per-session services can then fail or reach the wrong place.
The second attempt runs the command as root and writes straight into the user’s home folder. Tilde expansion uses HOME, or the running user’s home when HOME is unset. In a root script, ~ therefore normally points at root’s home, not the user’s. Hard-coded paths under /Users avoid that, but anything the command creates there is then owned by root. That can cause permission problems later when the user’s own apps try to change those files.
Neither attempt checks whether anyone is signed in at all. A script that fires at the login window can quietly run its “user” command as root.
#What to do instead of sudo -u on its own
Split the job into three decisions, made in order every time the script runs. First, find out who owns the console. Second, refuse to go on if nobody does. Third, run each user command with both the user’s launchd context and the user’s identity.
The launchctl manual page describes asuser exactly. It runs a command in a context as close as possible to the target user’s bootstrap. The command adopts that user’s Mach bootstrap namespace, exception server and security audit session. It does not change the process’s UID or GID, and it does not adopt the user’s environment variables. Adding sudo -u inside it supplies the missing identity, and -H asks sudo to set HOME to the user’s home folder.
This pairing has a limit worth stating up front. On Apple’s developer forums, Apple’s Developer Technical Support calls asuser a legacy command that does not understand modern launchd constructs. It suits a single command for the person at the screen right now. It is the wrong base for anything that must run at every login or for every user.
#Setting up the run_as_user function
The script below is the whole pattern in one place. It sets a plain system PATH so that a root job does not depend on anyone’s shell setup. It also prints what it is doing, so the MDM’s script log shows which user it acted for.
1#!/bin/bash
2# Run one command as the user at the Mac's console.
3# The MDM runs this script as root.
4PATH=/usr/bin:/bin:/usr/sbin:/sbin
5export PATH
6
7console_user=$(stat -f %Su /dev/console)
8
9if [ -z "$console_user" ] || [ "$console_user" = "root" ]; then
10 echo "No logged-in user at the console. Nothing to do."
11 exit 0
12fi
13
14console_uid=$(id -u "$console_user") || {
15 echo "No UID found for $console_user. Stopping."
16 exit 1
17}
18
19run_as_user() {
20 launchctl asuser "$console_uid" sudo -u "$console_user" -H "$@"
21}
22
23echo "Script user: $(id -un). Console user: $console_user ($console_uid)."
24run_as_user id -unBuild it up on a test Mac in this order
- Run
stat -f %Su /dev/consolein Terminal while signed in. The%Suformat prints the owner of the file as a name, and the output should be your short user name. - Run
id -ufollowed by that name. It prints the numeric UID thatasuserexpects. - Save the script above and run it with
sudo /bin/bash ./run-as-user.sh. Expect the line “Script user: root” followed by your own short name on the next line. - Replace the final
id -unwith the real command, using full arguments and no variables that came from outside the script.
Following along? Tap a step’s number to tick it off.
The exit choice for “nobody signed in” matters. Exiting 0 records the run as a success with a clear log line, which suits work that can wait for the next run. Exiting with a non-zero status makes the MDM flag the Mac, which suits work that must happen. Pick one deliberately and write it into the script’s description.

#A user setting with a backup before the change
Most real uses change something, such as a preference in the user’s defaults. The defaults command acts on the defaults of the user who runs it. That is why it must run through run_as_user rather than as root. The example below uses a placeholder domain, com.example.helpdesk, so swap in your own.
1domain="com.example.helpdesk"
2backup="/private/var/tmp/${domain}.${console_user}.plist"
3umask 077 # keep the backup readable by root only
4
5# Back up the user's current settings as XML before any change.
6run_as_user defaults export "$domain" - > "$backup" || exit 1
7
8run_as_user defaults write "$domain" ShowWelcome -bool false
9
10# Read the value back as the user to confirm it landed.
11value=$(run_as_user defaults read "$domain" ShowWelcome)
12if [ "$value" != "0" ]; then
13 echo "Expected 0, read '$value'. Restoring the backup."
14 run_as_user defaults import "$domain" - < "$backup"
15 exit 1
16fi
17echo "ShowWelcome is off for $console_user."The read-back is deliberate. The launchctl manual page does not say whether asuser passes on the inner command’s exit status. Reading the value back as the user is a more reliable test than any exit code. It proves the change is visible in the user’s own defaults.
#Who can change the script and what it may run
A script like this is a root process that starts commands in someone else’s session. Treat its contents with the same care as a sudo rule. Limit who can edit or reassign it in the MDM to the people who own Mac scripting. Keep every version in source control, with a reviewer.
Keep the command list fixed inside the script. Never build the command from a file in the user’s home or a parameter typed by a help desk agent. The same goes for anything else a non-administrator can change. Never pass a variable to bash -c through run_as_user, because that turns any text in the variable into a command run in the user’s session.
Keep the user commands to things the user could do for themselves. If a step needs root, run it as root outside run_as_user, so that the log shows clearly which steps had which rights.
#Prove the command ran as the user
Check three things on a test Mac before the script goes near the fleet. Each check is read-only.
- Run the base script with your account signed in. The output should show root for the script, then your short name for the user command.
- Sign out, then let the MDM run the script while the login window shows. Expect the “No logged-in user at the console” line and no user command in the log.
- After the preference example, run
defaults read com.example.helpdesk ShowWelcomeas yourself in Terminal. It should print 0.
Treat launchctl print output as something for a person to read, not for a script to parse. The manual page says the output of the newer subcommands is not an API and may change between releases.
#Where it goes wrong on real Macs
A few failures account for most of the trouble with this pattern.
- Using asuser without sudo -u. The command runs in the user’s session as root, so any file it writes in the user’s home folder is owned by root.
- Running at the login window. With nobody signed in, the script must not carry on. The root check above is the stop condition, so keep it even when the MDM “always” runs the script after login.
- Expecting every signed-in user. Apple’s console user API covers the primary console only, and reports nothing about sessions switched out with fast user switching. Screen Sharing sessions are not on the console either. The script reaches one user: the one at the screen.
- Using ~ or $HOME in the root part. Both point at root’s home folder. Build user paths from the user’s name, or let
sudo -Hset HOME inside the user command. - Parsing launchctl output. It is not a stable format, so a script that greps it can break after an update.

#When a LaunchAgent is the better tool
If the work must happen at every login, for every user on a shared Mac, or before anyone signs in, use a LaunchAgent. A property list in /Library/LaunchAgents is a per-user agent provided by the administrator. launchd starts it inside each user’s own session, so there is no console user to look up.
The LimitLoadToSessionType key controls where an agent loads. Aqua agents load only after a user signs in at the GUI. LoginWindow agents load while the login window is showing and currently run as root. Apple’s Developer Technical Support recommends this design over asuser for GUI work.
Their suggested agent is set to Aqua and LoginWindow, so the system starts one in each GUI login session. Setting one up is much like running a root script on a schedule with a LaunchDaemon, with the plist in /Library/LaunchAgents.
#Undo a preference the script changed
Every change in this pattern has its backup taken first. To roll a user back, run run_as_user defaults import com.example.helpdesk - < "$backup" from a root script while that user is signed in. Then read the key back as the user to confirm the old value has returned.
If the export fails, the script stops before writing anything, which is the safe outcome. If the domain held nothing before the change, there is little to restore. Remove the one key the script added with run_as_user defaults delete com.example.helpdesk ShowWelcome instead.
For the script itself, unassign the new version in the MDM and reassign the previous one to the same group. Keep the backup files until the pilot group has run the new version without a failed read-back.
#How to tell it worked across the fleet
Track the script’s results by outcome rather than by a single pass or fail. Three counts tell you most of what you need:
- runs that acted for a named user and read the value back correctly;
- runs that found no user at the console and exited without changes;
- runs that failed the read-back and restored the backup.
A high share of “no user” runs means the MDM is firing the script at the wrong time. In that case a LaunchAgent is probably the right home for the work. Any read-back failure deserves a look at that Mac before the next run.
For root-owned leftovers, run sudo find /Users/jsmith/Library -user root on a pilot Mac before and after rollout, swapping in the user’s short name. The -user test matches files that belong to the named user, and this list should not grow. If the script logs to the unified log, triaging launchd and login window log noise helps separate its lines from the usual chatter.
#Before you go live with a user-context script
- The script stops cleanly when the console owner is root or empty, and its exit code for that case is a deliberate choice.
- Every user command goes through
launchctl asuserandsudo -u, never one without the other. - No user command is built from input a non-administrator can change.
- Each change has a backup taken first and a read-back after.
- The script ran on a test Mac with the expected output, then on a pilot group.
- Recurring, per-login or pre-login work has moved to a LaunchAgent instead.
About this page
Credited to
Dates
Published
Sources
Corrections
No corrections are listed for this page. Some review sweeps corrected pages without naming each one; those are in the corrections log.
Recommended reading
More from KBY that goes with this article.
Related articles
Automation & Scripting
Run a Root Script at Boot or on a Schedule With a macOS LaunchDaemon
Run a bash script as root at boot or on a timetable with a LaunchDaemon: plist keys, owner and mode, launchctl bootstrap, print, kickstart and bootout rollback.
ReadSecurity & Operations
Make Users Request, Not Release, Quarantined Phishing Mail with Defender for Office 365 Quarantine Policies
Swap the full-access default for a request-release quarantine policy on phishing verdicts, then approve or deny user requests from the Quarantine page.
ReadSystems Engineering
Find Stale Computer Accounts in Active Directory with PowerShell, and Disable Them Before You Delete
List computer accounts that have not logged on for 90 days, record them, disable and quarantine them in stages, and keep a clear way back.
ReadDiscover more
Was this useful?
Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.
Operate smarter, with fewer recurring tickets.
Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.


Comments
Add a thoughtful note on Run a Command as the Logged-In User From a Root Mac Script. Comments are checked for spam and held for moderation before appearing.