简体   繁体   中英

crontab not running shell script

Struggling to get crontab to execute a shell script on my Raspberry Pi. The script runs fine if executed with bash (it's executing a python script that runs in a virtual environment).

Here's what I've tried

crontab -e
* * * * * /home/pi/bash/myshell.sh

And the shell script...

#! /bin/bash
cd /home/pi/projects/scripts
source activate myEnv
python pyscript.py
source deactivate

This works fine...

bash /home/pi/bash/myshell.sh

I also tried editing the root cron tab file directly with sudo nano /etc/crontab but this also didn't work. What am I missing here?

You need to give executable permissions to the shell script:

chmod u+x /home/pi/bash/myshell.sh

The above sets permission for the file to be executed only by the owner or by the root user.

Thanks for everyone that took the time to answer. So the problem was not with crontab at all but was actually an issue with Python virtual environments. Using source activate was not working with crontab. The solution was to modify the shell script so that it directly uses the Python in the specified virtual environment. For example..

#! /bin/bash
cd /home/pi/scripts
/home/pi/berryconda3/envs/myEnv/bin/python pyscript.py

Also I had logging done within Python but because it crashed early in the script they were never written so I incorrectly assumed the crontab was not executing correctly. I have since discovered that it is a very good idea when working with crontab to log what's going on directly from cron like this...

* * * * * /home/pi/bash/myshell.sh >> /home/pi/logs/cronlog 2>&1

This way I could actually see what was going wrong (ie Python was throwing ModuleNotFoundError ).

There's a much better answer on this here that is worth looking at. I'll mark this question as a duplicate.

Set path at the beginning of your script - for example:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM