如何添加在所有我的cron作业之前运行的预挂机和挂机后脚本? [英] How do I add pre-hook and post-hook scripts that run before all of my cron jobs?
问题描述
假设我有以下cron条目:
Suppose I have the following cron entry:
* * * * * /bin/date
现在假设我想要在cron作业运行之前和之后运行的脚本。
Now suppose that I want scripts that run both before and after the cron job runs.
我可以修改cron条目如下:
I could modify the cron entry to look like this:
* * * * * /bin/prehook ; /bin/date ; /bin/posthook
或者如果我想要prehook的退出代码来确定日期命令运行,我可以这样做:
Or if I wanted the exit code of the prehook to determine whether or not the date command runs, I could do this:
* * * * * /bin/prehook && /bin/date ; /bin/posthook
但是,我在寻找一个解决方案,到所有cron作业,而不需要编辑每个crontab;我认为这类似于许多版本控制系统中看到的预提交和后提交的钩子。
However, I'm looking for a solution that I might be able to apply globally to all cron jobs without editing every single crontab; I see this as analogous to pre-commit and post-commit hooks that you see in many version control systems.
推荐答案
我使用的是 crontab
条目总是由一个脚本名称组成,如:
The system I use is that a crontab
entry always consists of a single script name, such as:
3 1 * * * /home/me/bin/Cron/daily
/ home / me / bin / Cron / daily
中的脚本实际上是指向单个脚本 runcron
的链接看看它是什么(例如 daily
)。它设置了我的环境(因为 cron
不会设置超过非常最小的环境),然后运行 / home / me / bin / daily
。如果(当)我需要调试cron或添加预钩子或后挂钩,我可以做到全局(通过修改 / home / me / bin / Cron / runcron
)或本地(通过将 runcron $ c $>临时修改为
/ home / me / bin / Cron / daily
c> script)。这种灵活性在我需要它的那些场合非常有用,并且不涉及实际 crontab
条目的任何变化。
The script in /home/me/bin/Cron/daily
is actually a link to a single script, runcron
, which looks at what it is called (e.g. daily
). It sets my environment (since cron
does not set more than the very barest of minimal environments), and then runs /home/me/bin/daily
. If (when) I need to debug cron, or add pre-hooks or post-hooks, I can do it globally (by modifying /home/me/bin/Cron/runcron
) or locally (by making /home/me/bin/Cron/daily
temporarily into a modified copy of the normal runcron
script). This flexibility is very useful on those occasions when I need it, and doesn't involve any change in the actual crontab
entry.
如果提供了参数,我的脚本会传递参数。我从来没有找到足够的理由使用该功能,但长期。我有每日
,工作日
,每周
code> monthly 。 (另请参见我在哪里可以设置crontab的环境变量使用?)
My scripts do relay arguments if they're provided. I've never found sufficient reason to use that functionality in the long term, though. I have entries for daily
, weekday
, weekly
and monthly
. (See also Where can I set environment variables that crontab will use?)
这篇关于如何添加在所有我的cron作业之前运行的预挂机和挂机后脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!