首页 > 解决方案 > 如何使用 cron 运行 linux 命令

问题描述

我有几个 linux 命令,我想每天早上使用 cron 运行一次。不知道如何做到这一点。

我知道这需要使用 shell 来完成,但我不知道如何在 linux 中完成这一切。不过,我将能够使用 cpanel 创建 cron ......

这些是命令

rm -rf <directory>
mkdir <directory>
chmod 777 <directory>

标签: cron

解决方案


您可以在文件 script.sh 中使用此命令创建一个 shell 脚本,例如:

#!/usr/bin/bash

rm -rf <directory>
mkdir <directory>
chmod 777 <directory>

<others commands or logical instructions>...

在 linux 中,您可以在 crontab、crontab -e命令或/etc/cron.d目录中添加 cron 作业。不同之处在于,使用命令 crontab -e,cron 作业将设置为执行 crontab -e 并在 cron.d 中添加 cron 作业文件的用户,您需要将用户置于 cron 作业命令之前。

将在上午 06:00 执行的 cron 作业示例。

使用 crontab -e:

0 6 * * * /usr/bin/bash /path_to_script/script.sh

在 /etc/cron.d 中创建一个文件:

0 6 * * * root /usr/bin/bash /path_to_script/script.sh

或者,您可以将命令放在您的 cron 作业中,如下所示:

0 6 * * * rm -rf <directory> && mkdir <directory> && chmod 777 <directory>

注意:记得把要删除或创建的目录的绝对路径

PS:您可以使用任何语言编写脚本并使用 shell 调用,如带有shell_exec()函数的 php 或system()perl 的函数。


推荐阅读