第一次使用crontab常會有跑不起來的困擾, 即使你已經在別台機器上跑過,
只要換了一個系統, 就會遇到fail run with cron, but work in terminal的情況!
以下是擷取自http://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work
要注意的就是就是比對cron job的env跟terminal的差異........
(* * * * * env > /tmp/env.output 這招真好用, 除了dump env之外, 還可以順便證明crontab到底會不會跑....)
最後還有建議在crontab -e時加PATH的例子,
不過我的作法比較暴力,
是在script 直接source /home/my-accunt/.bashrc 比較快!!!!!
Cron passes a minimal set of environment variables to your jobs. To see the difference, add a dummy job like this:
* * * * * env > /tmp/env.output
Wait for /tmp/env.output
to be created, then remove the job again. Now compare the contents of/tmp/env.output
with the output of env
run in your regular terminal.
A common "gotcha" here is the PATH
environment variable being different. Maybe your cron script uses the command somecommand
found in /opt/someApp/bin
, which you've added to PATH
in/etc/environment
? cron does not read that file, so runnning somecommand
from your script will fail when run with cron, but work when run in a terminal.
To get around that, just set your own PATH
variable at the top of the script. E.g.
#!/bin/bash
PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# rest of script follows
Some prefer to just use absolute paths to all the commands instead. I recommend against that. Consider what happens if you want to run your script on a different system, and on that system, the command is in/opt/someAppv2.2/bin
instead. You'd have to go through the whole script replacing/opt/someApp/bin
with /opt/someAppv2.2/bin
instead of just doing a small edit on the first line of the script.
You can also set the PATH variable in the crontab file, which will apply to all cron jobs. E.g.
PATH=/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
15 1 * * * backupscript --incremental /home /root