简体   繁体   English

crontab 未运行 shell 脚本

[英]crontab not running shell script

Struggling to get crontab to execute a shell script on my Raspberry Pi.努力让crontab在我的 Raspberry Pi 上执行 shell 脚本。 The script runs fine if executed with bash (it's executing a python script that runs in a virtual environment).如果使用 bash 执行脚本,则该脚本运行良好(它正在执行在虚拟环境中运行的 python 脚本)。

Here's what I've tried这是我尝试过的

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

And the shell script...还有 shell 脚本...

#! /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.我还尝试使用sudo nano /etc/crontab直接编辑根 cron 选项卡文件,但这也不起作用。 What am I missing here?我在这里想念什么?

You need to give executable permissions to the shell script:您需要赋予 shell 脚本可执行权限:

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.上面设置了文件的权限,只能由所有者或 root 用户执行。

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.所以问题根本不在于 crontab,而实际上是 Python 虚拟环境的问题。 Using source activate was not working with crontab.使用source activate不适用于 crontab。 The solution was to modify the shell script so that it directly uses the Python in the specified virtual environment.解决方法是修改 shell 脚本,使其在指定的虚拟环境中直接使用 Python。 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.此外,我在 Python 中完成了日志记录,但因为它在脚本的早期崩溃,所以它们从未被写入,所以我错误地认为 crontab 没有正确执行。 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...从那以后,我发现使用crontab像这样直接从 cron 记录正在发生的事情是一个非常好的主意......

* * * * * /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 ).这样我实际上可以看到出了什么问题(即 Python 正在抛出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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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