1

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.

3

3 Answers 3

4

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

4
  • I'll definitely take a look at Lingon!
    – gentmatt
    Commented Dec 20, 2011 at 19:30
  • Thanks, how would I go about adding a command starting 'sudo' via launchctl (given I'd need to supply my sudo password)?
    – tog22
    Commented Dec 21, 2011 at 15:17
  • @tog22 in the plist see the key UserName to say which user the command should run as
    – mmmmmm
    Commented Dec 21, 2011 at 15:24
  • You can run launchd services as root by saving them to /Library/.
    – Lri
    Commented Aug 19, 2012 at 10:29
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"

2
  • Thanks, but I need to 'sudo' my command - presumably there's no way to do that with AppleScript as I'd need to enter my password after the command?
    – tog22
    Commented Dec 21, 2011 at 15:16
  • 1
    This can be done by adding with administrator privileges password "123456" at the end of the command. If you don't want to save the password in the script, just write with administrator privileges. Then you'll be prompted for a password at runtime. I'll edit my answer.
    – gentmatt
    Commented Dec 21, 2011 at 15:40
1

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

@reboot /path/to/script.sh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .