Run command on startup / login (Mac OS X)

To run a command on start up on OS X, you need to use launchd.

If you don't want to use Lingon, you need to create a launchd Property List. This is an XML file, so you can do it with your favourite text editor or alternatively you can use the Property List Editor that's installed with the Mac OS X Dev Tools. Create the following:

<?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>some.meaningful.name</string> <!-- org.mongodb.mongodb perhaps? -->

    <key>OnDemand</key>
    <false/>

    <key>UserName</key>
    <string>anAppropriateUser</string>

    <key>GroupName</key>
    <string>anAppropriateGroup</string>

    <key>ProgramArguments</key>
    <array>
            <string>/Applications/MongoDB/bin/mongod</string>
            <string>--dbpath</string>
            <string>/usr/local/mongo/data</string>
            <string>--fork</string>
            <string>--logpath</string>
            <string>/usr/local/mongo/log</string>
    </array>
</dict>
</plist>

Save this in /Library/LaunchAgents/some.meaningful.name.plist (you will need an administrator account and/or sudo), then open a terminal and do:

sudo launchctl load /Library/LaunchAgents/some.meaningful.name.plist

This will cause launchd to load the item which will cause it to start MongoDB on boot. As a bonus, launchd will monitor it and, if it exits for any reason, it will be re-started. To get rid of the item simply replace load in the above command with unload.


Another simple solution from Stack Overflow: You can:

  • Start Automator.app;
  • Select "Application";
  • Click "Show library" in the toolbar (if hidden);
  • Add "Run shell script" (from the Actions/Utilities);
  • Copy-and-paste your script into the window;
  • Test it;
  • Save it somewhere: a file called your_name.app will be created);
  • Depending your MacOSX version:
    • Old versions: Go to System Preferences → Accounts → Login items, or
    • New version: Go to System Preferences → Users and Groups → Login items (top right);
  • Add this newly-created app;

Log off, log back in, and you should be done. ;)


Officially none of these. The Apple suggested way is to use launchd. Guis to set this up include lingon and Launch Control

As for the files you mention the ones in the home directory ~/.bashrc, ~/profile, ~/.bash_profile are only started when you login via a terminal. The ones in /etc are run by the shell starting for all users before the ones in home directory but only when a user login is made.. bash manual

The Unix startup script involved /etc/rc* but for OSX just use the launchd stuff

Tags:

Macos

Boot