【问题标题】:crontab doesn't run a bash scriptcrontab 不运行 bash 脚本
【发布时间】:2021-04-03 22:53:13
【问题描述】:

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

我有这个简单的 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     

【问题讨论】:

  • 查看man 5 crontab,了解如何配置 cron 条目。 PATH 绝对不在正确的位置。
  • 谢谢你,但我不得不承认我不知道如何纠正这个问题

标签: bash cron


【解决方案1】:

脚本名为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

让我知道你是怎么做的。

【讨论】:

  • 非常感谢您的快速答复。对不起,这是一个错字,它一直是 run2.sh !我所做的是进入我的目录(/home/ubuntu/test_code),编写 crontab -e 并编辑文件。我使用你的设置(只需使用“* * * * *”就不必等待 2 小时),但它仍然不起作用
  • 通过附加&>cron.log将命令的输出发送到文件
  • 也许这很有用:当我手动运行脚本时,它可以工作(我想要的所有文件都已创建并移动到正确的文件夹),但它告诉我:run2.sh: 1 : !/bin/bash: 未找到
  • 听起来您缺少脚本的第一个字符,应该是 #。编辑run2.sh 并验证第一个字符实际上是#
  • 刚刚搞定,/home/ubuntu 中已经创建了cron.log 文件。但它是空的
猜你喜欢
  • 2017-12-02
  • 2018-08-10
  • 2013-04-19
  • 2014-02-20
  • 2022-01-05
  • 2017-12-12
  • 2020-10-20
  • 2016-10-20
相关资源
最近更新 更多