launchd: Start and keep alive a script in OS X

04 Feb 2011

You want to start a script, and make sure it always keeps running in the background.

First write a file org.myscript.plist containing:

<?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>KeepAlive</key>
        <true/>
        <key>Label</key>
        <string>org.myscript</string>
        <key>ProgramArguments</key>
        <array>
                <string>/path/to/my/script.sh</string>
        </array>
</dict>
</plist>

Copy or move your file into ~/Library/LaunchAgents/ and then run:

$ launchctl load org.myscript

Finally use something like:

$ launchctl list | grep myscript

if you want to verify that it is indeed running.

The script will continue to run forever, restarted if necessary, even after you login/logout of your user session.