Run scripts on Mac using Launchd

Run scripts on Mac using Launchd

Let say you have just completed a neat piece of script that do whatever you want it to do. How can you let it run everytime your Mac startup? Launchd!

To use Launchd, you will need to first create a .plist file in the following format (you can try out more features following Apple Developer Doc:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
   <dict>
      <key>Label</key>
      <string>YOUR LAUNCH AGENT NAME</string>

      <key>StartInterval</key>
      <integer>SECONDS</integer>

      <key>StandardErrorPath</key>
      <string>LOG FILE FOR stderr</string>

      <key>StandardOutPath</key>
      <string>LOG FILE FOR stdout</string>

      <key>ProgramArguments</key>
      <array>
         <!--How to run your script-->
         <string>/bin/bash</string>
         <string>/Path/to/Script.sh</string>
      </array>

      <key>RunAtLoad</key>
      <true/>
   </dict>
</plist>

Note that setting the script with relative directory like ~/Path/to/script might not work properly and you might need to switch to absolute directory. This also applies to the script you want to run: you will also might want to use absolute directory within it.

After creating the .plist, you can then put it under ~/Library/LaunchAgents and use launchctl to load it:

launchctl load /path/to/plist

You can that check system.log output or use launchctl list | grep YOUR_LAUNCH_AGENT_NAME to see whether the agent is loaded and running properly.

Here is a portal to some of the bashhelper scripts I am working on, feel free to clone and test them out!

Subscribe to TheXYZLab Blog

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe