Trouble creating directory from script run by launchd

launchdscriptterminal

I have a simple script that creates a new directory based on the date then copies a set of files to that directory. It runs fine from Terminal. When I set it up to run as a UserAgent it fails. The error log shows that has changed to paths from /Users/Study/xxx to /var/root/xxx. I've tried running it as root from Terminal and it still works. I've ensured root is not the owner of the script file. I've changed my original path of ~/xxx to the /Users/Study/xxx but for some reason when run from launchd it changes the path. Any ideas?

script:

!/bin/bash

MO=$(date +%d%B%Y)
mkdir /Users/Study/Dropbox/SPID_backups/$MO
cp -r /Users/Study/WebDevelopment/SPID/*.* /Users/Study/Dropbox/SPID_backups/$MO

launchctl plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.spidbackup</string>
    <key>Program</key>
    <string>/Users/Study/Library/Scripts/spidbackup.sh</string>
    <key>StandardErrorPath</key>
    <string>/tmp/com.spidbackup.err</string>
    <key>StandardOutPath</key>
    <string>/tmp/com.spidbackup.out</string>
    <key>StartCalendarInterval</key>
    <array>
        <dict>
            <key>Hour</key>
            <integer>17</integer>
            <key>Minute</key>
            <integer>11</integer>
        </dict>
    </array>
    <key>WorkingDirectory</key>
    <string>/Users/Study</string>
</dict>
</plist>

Best Answer

You backup task is (very) user-specific and no system service, so the proper location for the launch agent is ~/Library/LaunchAgents/. If you put the plist in /Library/LaunchAgents it will run on behalf of every user logged in at ~ 5.11pm - which will fail for most users because they probably can't access some or most of your user folders/files.


Use a proper shebang in the script #!/bin/bash.. and make the script executable: chmod +x /Users/Study/Library/Scripts/spidbackup.sh.

Completely remove the plist from the launchctl db with sudo launchctl remove com.spidbackup and launchctl remove com.spidbackup. Move the plist to /Users/Study/Library/LaunchAgents/, chown/chmod it to your user and remove the key WorkingDirectory and the associated string.

Finally reload the agent with:

launchctl load /Users/Study/Library/LaunchAgents/com.spidbackup.plist 

The proper permissions/ownerships for the files are finally:

ls -l /Users/Study/Library/Scripts/spidbackup.sh
-rwxr-xr-x  1 study  staff  ... spidbackup.sh

or

-rwx------  1 study  staff  ... spidbackup.sh

and

ls -l /Users/Study/Library/LaunchAgents/com.spidbackup.plist 
-rw-r--r--  1 study  staff  ... com.spidbackup.plist

assuming Study is your user name.

Please also check capitalization (e.g. study vs. Study).