Is it possible to unload or load a Launch Agent being run as a user? I know all scripts are executed as root. We have an auto-save utility that is run via launch agent at ~/Library/LauncheAgents and we need to unload it to stop it and then load it when ready to start it back up.
I tried using the following script and although it shows that it runs successfully, it doesn't appear to unload the agent. Can anyone point out if the script is flawed or if what we are trying to do just isn't possible?
#!/bin/bash
## Get logged in user and UID
loggedInUser=$(stat -f%Su /dev/console)
loggedInUID=$(id -u $loggedInUser)
## Put the name of the process to call on here. Run "ps axc" to look for the process name
SaveMeProcess="savemed"
## Put the LaunchAgent plist path and name here
SaveMePlist="/Library/LaunchAgents/com.chapman.SaveMe.plist"
if [ "$loggedInUser" != "root" ]; then
echo "A user is logged in. Checking for agent process..."
## Check for agent as user
FCProcCheck=$(/bin/launchctl asuser $loggedInUID sudo -iu $loggedInUser ps axc | grep "SaveMeProcess" 2>&1 >/dev/null; echo $?)
if [ "$FCProcCheck" != 0 ]; then
echo "Agent is not running. Reloading..."
/bin/launchctl asuser $loggedInUID /bin/launchctl unload "$SaveMePlist"
else
echo "Agent process is running. Nothing to do."
exit 0
fi
else
echo "No-one logged in. Cannot check on process."
exit 0
fi