crontab 不运行 bash 脚本

时间:2021-04-03 13:21:07

标签: bash cron

我阅读了很多其他主题并尝试了很多东西,但我仍然无法工作。

我有这个简单的 run2.sh 脚本:

#!/bin/bash
python3 my_script.py
wait;
sudo mv /home/ubuntu/test_code/csv_created_by_python_script.csv /var/www/html

当我进入目录并写入时它完美地工作

sh run2.sh

但它不会像我想要的那样运行(每两个小时)。我尝试了某种 crontab,比如

* * * * * /home/ubuntu/test_code/run2.sh
* * * * * PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /home/ubuntu/test_code/run2.sh

但我想我不明白所有这些路径的东西...

编辑:cronfile

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be 
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow command

#1 * * * * PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /home/ubuntu/test_code/run2.sh
* * * * * test_code/run2.sh &>cron.log
* * * * * pwd &>pwd.log     

1 个答案:

答案 0 :(得分:0)

脚本名为 run.sh,但 cron 条目尝试运行 run2.shcron 条目是否指的是正确的脚本?

您没有说明您正在与哪个用户的 crontab 合作。如果它是针对用户 ubuntu,并且是您用于登录的用户 ID,那么 crontab -e 是编辑 crontab 的命令。如果您使用 sudo,那么您会影响具有不同权限的 root 用户 crontab

您不需要两个条目即可实现此目的。只需删除最后一行。我将向您展示如何在下面的 crontab 中设置环境变量。

指定 * * * * * 表示“每天 24/7 每天每分钟运行我的程序”。要改为每 2 小时运行一次,请使用 0 */2 * * *。要了解更多信息,请参阅 https://crontab.guru/every-2-hours

Cron 从您的主目录运行命令,因此您可以使用相对路径在用户 ubuntu 的主目录下运行程序。

请注意,我设置了 PATH 环境变量,由所有 cron 条目使用,这可能不是必需的,但应该不会造成任何伤害:

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

0 */2 * * * test_code/run2.sh

要调试,像这样附加 &>cron.log

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

0 */2 * * * test_code/run2.sh &>cron.log

然后从终端类型:

$ tail -f cron.log

告诉我你是如何处理的。