Running bash scripts on cron
Wow, that drove me crazy.
While having a command execute fine in the crontab, the script wasn’t. Here is what my crontab looked like.
$ crontab -l
* * * * * echo $(date) > somefile # this one was working
* * * * * /bin/bash /full/path/to/somescript.sh # this one wouldn't
somescript.sh
even contains a shebang, and it still didn’t work. Then I read this post and finally understood what was wrong by randomly visiting the home directory:
The script was executing all along, but putting the result in ~/
.
From the beginning
I am working on WSL. You edit crontab by running
$ crontab -e
and start the daemon with
$ /etc/init.d/cron start
Putting the following in the crontab can help you with debugging
#Identify whats in the path variable in the context of your script
* * * * * echo $PATH >> ~/cron.log
#Identify the shell being used in your script
* * * * * echo $SHELL >> ~/cron.log
#Identify the working directory your cron job executes in by default (usually user home directory)
* * * * * echo $(pwd) >> ~/cron.log