I'd like to have a simple bash script run (regardless of whether anyone is logged in or not) akin to putting it in /etc/cron.daily/ on Linux, but on Mac OS X Mountain Lion 10.8.4. If it's possible, how? All it needs to do is copy (and maybe bzip) a file.
- 24,199
- 39
- 117
- 171
- 31
- 1
- 5
-
1cron should run without being logged in. cron works the same way anywhere. – Journeyman Geek Aug 16 '13 at 15:35
-
2Try a `crontab -e`. Create a job to touch a file in in a few minutes. Log out. Wait those minutes. Check if the file has been created. (Optionally: remove the now useless cron job :) ) – Hennes Aug 16 '13 at 15:39
-
you don't have to be logged in but the computer does need to be in the active mode, meaning not closed – amphibient Aug 16 '13 at 15:54
2 Answers
Cron is officially deprecated, so you should use launchd.
There is a tutorial at apple: https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
A good starting point for explaining where to put the plist file
https://alvinalexander.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs
A bit more details can be found at
Two things that got/confused me:
1) Pay attention between the difference between Program and ProgramArgments
2) If the job you want to run is a script, it needs to have the #!/bin/sh, otherwise launchd cannot start it, and you will end up with a confusing exit/status-code 78.
- 101
- 2
Using cron, you can edit the superuser's crontab with for example EDITOR=nano sudo crontab -e. When I tried adding a line like * * * * * say aa, the say command was run even after I logged out to the login window.
Using launchd, save a property list like this as for example /Library/LaunchAgents/test.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>test</string>
<key>ProgramArguments</key>
<array>
<string>say</string>
<string>bb</string>
</array>
<key>StartInterval</key>
<integer>10</integer>
</dict>
</plist>
Then run sudo chown root /Library/LaunchAgents/test.plist and sudo launchctl load /Library/LaunchAgents/test.plist. The say command scheduled by launchd was also run when I logged out to the login window.
- 40,894
- 7
- 119
- 157
-
If I set the script to run while I'm logged in, it seems to work, but not when I'm logged out. Also, I can't find any entry in the log for it to see what went wrong. – Lido Aug 30 '13 at 09:48
-
1Both methods worked for me when I tried logging out to the login window. If you mean the cron log, you can enable logging by [editing com.vix.cron.plist](http://superuser.com/questions/134864/log-of-cron-actions-on-os-x/135262#135262). If you mean launchd, you can save the stderr or stdout of the program to a log file by adding a StandardErrorPath or StandardOutPath key. See `man launchd.plist`. – Lri Aug 30 '13 at 10:33