Ubuntu – Cannot run bash script from crontab when it works from command line bash

bashcronscripts

I have a strange problem of being to able to run a bash script from commandline 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 fails with sh with following error:

jmeter-cron-randomise.sh: 7: jmeter-cron-randomise.sh: arithmetic expression: expecting primary: "  % 1 "

Having googled the problem it seems like stand shell doesn't have the same maths operators like % (modulus) like bash. Not sure why the cron job is failing in the script? i am assumming its because its not using the bash shell? It's definitely being fired by the cron daemon (can see it in /var/log/syslog ). Any help much appreciated.

script causing the problems

#!/bin/bash
echo Running the jmeter-cron-randomiser script


script="/home/xxxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/jmeter-cron.sh"    

min=$(( 1 * 1 ))
rmin=$(( $RANDOM % $min ))

echo  "min = ${min}";
echo  "rmin = ${rmin}"

at -f "$script" now+${rmin}min

Best Answer

I note in the crontab(5) man page, this:

The ``sixth'' field (the rest of the line) specifies the command to be run. The entire command portion of the line will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile.

So, you may want to specify bash either with

SHELL=/bin/bash

or, as the above affects all cron scripts, this

* * * * 1-5 root bash /home/xxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/jmeter-cron-randomise.sh >> /home/xxxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/cron.log
# ...............^^^^
Related Question