首页 > 解决方案 > 除非由 sh 命令调用,否则 Cron 脚本不起作用

问题描述

我有一个脚本保存在名为 file.sh 的文件中它由命令执行

chmod +x file.sh

文件.sh

#!/bin/sh
find /var/log/*.gz  -printf "%T@ %Tc %p\n"|sort -n|tail -n +6|sudo xargs rm|echo"test"|wall

我正在尝试通过 cron 作业执行它。

crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
* * * * * root /etc/file.sh

cron作业每分钟都会启动脚本,我在终端中得到回声。

但是xargs rm 不起作用。我知道为什么。

当我执行命令 sudo sh file.sh 时,没问题,文件被删除。

请帮我找出脚本在 cron-job 中不起作用的原因。真奇怪。

谢谢你 !

标签: linuxbashshellcron

解决方案


问题是你的printf陈述......我相当肯定你也应该rm在root的邮件中看到错误消息,大意是: 1634986839.0000000000 Sun 24 Oct 2021 12:00:39 AM UTC /var/log/syslog.2.gz不存在。


推荐阅读