在 crontab 中实现判断不存在任务再添加任务可以按照以下步骤进行:
- 编写一个 shell 脚本,用于检查 crontab 中是否已存在指定的任务。如果该任务不存在,则在 crontab 中添加该任务。以下是示例脚本,其中需要替换
<job_command>
为你要添加的任务命令,<cron_schedule>
为你想设置的 cron 定时器表达式。
#!/bin/bash
(crontab -l | grep -v -F "<job_command>" ; echo "<cron_schedule> <job_command>") | crontab -
- 保存该脚本文件,例如
/path/to/check_and_add_cron.sh
,并添加可执行权限:
chmod +x /path/to/check_and_add_cron.sh
- 使用 crontab 添加一个定时任务,每分钟执行一次该脚本:
* * * * * /bin/bash /path/to/check_and_add_cron.sh
这样,每分钟都会运行该脚本,检查 crontab 中是否已存在指定的任务。如果不存在,则会自动添加该任务到 crontab 中。注意,你需要修改示例脚本中的 <job_command>
和 <cron_schedule>
以适应你自己的需求。
至此,已经完成了在 crontab 中判断不存在任务再添加任务的操作。
留言