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

You likely need to tell cron that the shell to use is the bash shell as it defaults to sh. You can do that for all crontab entries by putting this line in your crontab:

SHELL=/bin/bash

Note that this will cause all scripts in the crontab to be run under bash which may not be what you want. If you want to change the crontab line itself to just run 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 have also caused stderr to be written to the cron.log file (2>&1) which may not be what you want but is pretty common practice. This may help you further diagnose errors from the script.


In case this helps anyone: for me this appeared to be because I had ended up with "DOS" line endings (CR-LF) instead of "unix" line endings (LF). This can be checked using od or your favourite hex dump tool, e.g.:

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" from working because it's interpreted as part of the shell executable's filename.

(The line endings themselves appeared because the file came from a git repository and was transferred via a Windows machine).

Tags:

Bash

Cron

Crontab