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.
-
possible duplicate of How can I run/stop/relaunch an application automatically, at boot/login/some other time?– mmmmmmDec 20, 2011 at 19:32
-
Not really a duplicate, as it's specific to terminal commands, covering how to sudo them, etc.– tog22Aug 18, 2012 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?– mmmmmmAug 18, 2012 at 11:48
3 Answers
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
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"
-
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?– tog22Dec 21, 2011 at 15:16
-
1This 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 writewith administrator privileges
. Then you'll be prompted for a password at runtime. I'll edit my answer.– gentmattDec 21, 2011 at 15:40
On mac, executing some script after startup can be accomplished by cron job:
@reboot /path/to/script.sh