【问题标题】:Run cron through shell script [closed]通过shell脚本运行cron [关闭]
【发布时间】:2017-08-11 13:24:31
【问题描述】:

我有一个名为 test.sh 的 shell 脚本。

#! /bin/bash
mysql -u root -p <<dbEmployee1
use dbEmployee1;
UPDATE EMPLOYEE SET EMPLOYEE_NAME = 'Cyndi' WHERE EMPLOYEE_ID ='1'; 
SELECT * from EMPLOYEE;
dbEmployee1

mysql -u root -p <<dbBooks
use dbBooks;
SELECT * FROM Author;
dbBooks

this tutorial 之后,我想做的是让我的脚本每 10 秒运行一次,但结果却低于。

seng@wseng:/$ */10 * * * * /home/seng/Desktop/test.sh
bash: proc/10: Is a directory

我在这里错过了什么或做错了什么?

编辑(执行crontab -e后)

# 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
* * * * * cd /home/seng/Desktop/test.sh

【问题讨论】:

  • 1) 不能使用cron来按秒进行调度; 2)您没有编辑您的 crontab,只是在命令行上随机放置了一个 cron 表达式
  • @RobbyCornelissen 我应该在哪里添加crontab?在脚本中?
  • 在终端中输入“crontab -e”。将出现一个新窗口。并将以下内容添加到您的 crontab 文件中 * * * * * cd /home/seng/Desktop/test.sh # 每分钟执行一次
  • @JohnJoe :按 Esc 并输入 :wq
  • 你不能在你的 shell 脚本中使用不带引号的通配符。可能使用\* 或引用此处的文档分隔符。另请参阅stackoverflow.com/questions/4937792/…(关于变量,但同样适用于通配符)。

标签: shell ubuntu cron ubuntu-16.04


【解决方案1】:

Cron 只允许最少 1 分钟。因此,要安排每 10 秒一次,您所能做的就是在另一个每 10 秒运行一次的脚本中调用该脚本。这可能不是正确的解决方案,但可以达到您的目的。

这是一个可以完成这项工作的简单脚本:

#!/bin/sh

while true
do

sh test.sh
sleep 10 

done

另外,请记住 test.sh 的执行时间。您可以相应地在脚本中更改睡眠时间。

如果你想在一分钟内运行它,那么这里是过程。

  • 您需要确保有权运行脚本的用户应该是当前登录用户。

  • 在命令行输入crontab -e(将打开一个编辑器)。输入以下内容

    * * * * * /absolute/path/to/the/script

现在关闭编辑器,首先按ESC 键和:wq,然后按ENTER

解释:

 .---------------- minute (0 - 59)
 |  .------------- hour (0 - 23)
 |  |  .---------- day of month (1 - 31)
 |  |  |  .------- month (1 - 12)
 |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
 |  |  |  |  |
*  *  *  *  * command to be executed

每个字母值都被提及并且可以相应地放置。

例如:

每分钟运行一次:

* * * * * command to be executed

每天午夜运行一些东西:

0 0 * * * command to be executed

您可以通过执行crontab -l 命令列出所有的cronjobs,并通过crontab -r 删除任何。

只需确保再做两件事,每次更改文件时重新启动 cron 守护程序 (service crond restart) 以及您将使用它执行的脚本的权限级别(查看 /var/mail/&lt;user&gt; 以获取日志)。

【讨论】:

  • 这充其量只是部分答案。 OP 还有许多其他问题,其中一些无关。
  • 是的,正如我已经提到的,这可能不是正确的解决方案,但足以满足要求。但是,您是正确的,因为在运行脚本的 shell 中应该一直启动并运行。
  • 如果我想让它运行一分钟,应该怎么做?
  • 请完成编辑。我已经用解释描述了这个过程:)
猜你喜欢
  • 2012-08-09
  • 2019-07-23
  • 2014-09-06
  • 1970-01-01
  • 2023-03-06
  • 2011-07-27
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多