Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

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.

share|improve this question
    
    
Not really a duplicate, as it's specific to terminal commands, covering how to sudo them, etc. –  tog22 Aug 18 '12 at 9:09
    
This question is "How can I run terminal commands on startup or login? " as is the other and where is sudo in either question? –  Mark Aug 18 '12 at 11:48
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
    
I'll definitely take a look at Lingon! –  gentmatt Dec 20 '11 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 Dec 21 '11 at 15:17
    
@tog22 in the plist see the key UserName to say which user the command should run as –  Mark Dec 21 '11 at 15:24
    
You can run launchd services as root by saving them to /Library/. –  Lauri Ranta Aug 19 '12 at 10:29
add comment

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"

share|improve this answer
    
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 Dec 21 '11 at 15:16
    
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 Dec 21 '11 at 15:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.