Apple has some restrictions in place to prevent access to LaunchAgents running in a user session context.
But you may want to load or refresh a LaunchAgent as part of your install without requiring the user to log out and back in.
I prefer not to require logouts and reboots in my installation packages. Where possible, I use munki’s unattended option so software installs silently and the user is not prompted.
After some experimentation, I came up with this hacky method of getting a LaunchAgent to load from a package being installed as root. If you have a cleaner way to accomplish this, please let me know. Update: Please see Per Olofsson’s comment for a much better method until I update this gist.
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 | |
| # if someone is logged in | |
| if who | grep -q console; then | |
| # get the logged in user's uid | |
| LOGGED_IN_UID=`ls -ln /dev/console | awk '{ print $3 }'` | |
| # use the uid and pgrep to find the Finder process id | |
| FINDER_PID=`pgrep -U ${LOGGED_IN_UID} Finder` | |
| # use launchctl bsexec to run applescript code in the same Mach bootstrap namespace hierachy as the Finder | |
| launchctl bsexec "${FINDER_PID}" osascript -e ' | |
| tell app "Finder" | |
| do shell script " | |
| launchctl unload -S Aqua /Library/LaunchAgents/com.company.agent.plist | |
| launchctl load -S Aqua /Library/LaunchAgents/com.company.agent.plist | |
| " | |
| end tell | |
| ' | |
| fi |