Search code examples
macosapplescriptlaunchdmacos-mojave

Run osascript (AppleScript) from launchd / launctl


I am trying to run a very simple AppleScript periodically using a launchd agent but it won't do anything aside from writing the AppleScript contents to stdout.

My launchd Agent at ~/Library/LaunchAgents/com.nn.test.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.nn.test</string>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/bin/osascript</string>
      <string>-e</string>
      <string>"display dialog \"Hi\""</string>
    </array>
    <key>RunAtLoad</key>
    <false/>
    <key>Debug</key>
    <true/>
    <key>StartInterval</key>
    <integer>7200</integer>
    <key>StandardErrorPath</key>
    <string>/tmp/test</string>
    <key>StandardOutPath</key>
    <string>/tmp/testout</string>
</dict>
</plist>

I am running by:

$ launchctl unload com.nn.test.plist
$ launchctl load com.nn.test.plist
$ launchctl run com.nn.test

Result is cat /tmp/testout

display dialog "Hi"

While /tmp/test is empty.

Expected behaviour would be that a dialog opens just like when I run the command directly in the shell (which works) but it seems nothing is happening. What am I doing wrong and why do I not see any error messages in any error log?

Might this have to do with Mojave's enhanced security model? Can't AppleScript be run from launchd agents any more?


Solution

  • I think you are doubly-stringified!

    You need:

        <array>
        <string>/usr/bin/osascript</string>
        <string>-e</string>
        <string>display dialog "Hi"</string>
        </array>
    

    and:

    launchctl start com.nn.test