Last active
April 5, 2016 18:48
-
-
Save opragel/1a45a0a7193ceca3399a to your computer and use it in GitHub Desktop.
Script to run LaunchAgent as the logged-in user from a script run with root privileges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
LAUNCH_AGENT_PATH="/Library/LaunchAgents/com.pritunl.client.plist" | |
currentUser=$(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");') | |
currentUserPID=$(pgrep WindowServer -m1) | |
currentUserUID=$(id -u "$currentUser") | |
osvers=$(sw_vers -productVersion | awk -F. '{print $2}') | |
if [[ $EUID -ne 0 ]]; then | |
printf "Run this script as root." | |
exit 10 | |
fi | |
if [ ! -f "$LAUNCH_AGENT_PATH" ]; then | |
printf "Launch agent not found at path: %s" "$LAUNCH_AGENT_PATH" | |
exit 20 | |
fi | |
if [[ $osvers -lt 10 ]]; then | |
launchctl bsexec "$currentUserPID" launchctl load "$LAUNCH_AGENT_PATH" > /dev/null 2>&1 & | |
elif [[ $osvers -eq 10 ]]; then | |
launchctl asuser "$currentUser" launchctl load "$LAUNCH_AGENT_PATH" > /dev/null 2>&1 & | |
elif [[ $osvers -ge 11 ]]; then | |
launchctl bootstrap "gui/$currentUserUID" "$LAUNCH_AGENT_PATH" > /dev/null 2>&1 & | |
else | |
printf "Things have gone terribly wrong. OS Version: %s" "$osvers" | |
exit 30 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment