Can't run bash script from crontab when running from bash command line
I have a weird problem about being able to run a bash script from the command line, but not from the crontab entry for root. I am running Ubuntu 12.04.
* * * * 1-5 root /home/xxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/jmeter-cron-randomise.sh >> /home/xxxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/cron.log
If I run the script from the cmd line using bash it works fine but sh
fails with the following error:
> jmeter-cron-randomise.sh: 7: jmeter-cron-randomise.sh: arithmetic
> expression: expecting primary: " % 1 "
Having googled a problem, it seems like the standard shell doesn't have the same math operators like% (module) like bash does. I'm not sure why the cron job isn't working in the script? I'm guessing it's because it doesn't use the bash shell? This definitely fired the cron daemon (you can see it in / var / log / syslog). Any help is greatly appreciated.
source to share
You probably need to tell cron that the shell to use is bash, which defaults to sh. You can do this for all crontab entries by placing this line in your crontab:
SHELL=/bin/bash
Note that this will cause all scripts in the crontab under bash to run, which may not be what you want. If you want to change the crontab line to just start bash, change it to this:
* * * * 1-5 root /bin/bash /home/xxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/jmeter-cron-randomise.sh >> /home/xxxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/cron.log 2>&1
Note that I also caused stderr to write to the cron.log file (2> and 1), which may not be what you want, but is a fairly common practice. It can help you further diagnose errors from within the script.
source to share
In case it helps anyone: for me it turned out to be because I ended up with "DOS" line endings (CR-LF) instead of "unix" line endings (LF). This can be checked using od or your favorite hex dump tool, for example:
od -c <script_file>
... and look for \ r \ n instead of just \ n.
It seems (and this article supports it) that the CR character stops the "shebang" because it is interpreted as part of the shell executable.
(The line endings appeared because the file came from a git repository and was ported through a Windows machine.)
source to share