Running terminal commands on startup/login

How can I run terminal commands on startup or login? On FreeBSD I believe you can do this using rc.d - is there an equivalent for the Mac? I know how to set up Login Items, but these only work for GUI applications, and there must be an elegant way to make terminal commands run without wrapping them in a GUI executable? As clarified below, I sometimes need to sudo these commands.


Solution 1:

OSX uses launchd to start Unix scripts and executables at boot or login.

New tasks are added via launchctl to update a plist

An easier way of doing this is to use the app Lingon now available on the Mac App Store or LaunchControl

Solution 2:

Use Apple Script.

The script would be like this:

do shell script "cd ~/Documents"

Create an application that uses this script. This application can be added to the login items. I've explained in detail how to do this here.

Executing commands in Apple Script as admin

Password prompt at runtime:

do shell script "rm -rf ~/Documents/Gorleben" with administrator privileges

Password saved within the script:

do shell script "rm -rf ~/Documents/Gorleben" with administrator privileges password "123456"

Solution 3:

On mac, executing some script after startup can be accomplished by cron job:

@reboot /path/to/script.sh