大网数据广告活动
服务器运维问答

find -delete works OK, but not with cron

· 52CE 我爱测

PLEASE NOTE : I have read all the similar questions re. cron, paths, env variables and so on, but have found none that offer solutions to my particular problem. I have a script that makes some MySQL dumps and then deletes old one…

问题原文

原帖链接 · TommyPeanuts · CC BY-SA 3.0

PLEASE NOTE: I have read all the similar questions re. cron, paths, env variables and so on, but have found none that offer solutions to my particular problem.


I have a script that makes some MySQL dumps and then deletes old ones like this:

/usr/bin/find "/home/bkp/dbdump" -name "*.gz" -mtime +5 -delete

(above command has been modified from my original command by suggestions from comments)

However, the files are never deleted when cron runs this script. The cron user is root.

Debugging notes

  • If I manually run the script in which the command appears, it deletes them as expected.

  • If I run the above find command on its own from the command line as root, it deletes them as expected (and with -print it returns a list of files older than 5 days as expected)

  • I have also added an explicit path statement to root's crontab, but
    that doesn't change anything.

  • Cron sends no error, and if I pipe the find operation to a log file,
    that comes up empty or is not created at all.

  • I'm using Ubuntu server 14.04.03 LTS.

社区高分解答

原帖链接 · Will · CC BY-SA 3.0

The problem is that crontab doesn't have $PATH set when it runs. You can actually provide it with a path by adding this to the top of the file opened via crontab -e:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

(or whatever PATH you'd prefer to use). This means you can avoid specifying the full paths to commands, directly from cron.

There are multiple problems with your original command. You're basically asking the shell to do the wildcard expansion, rather than find. Secondly, you're not providing a full path for rm; use /bin/rm or /usr/bin/rm, wherever it's located on your system (see which rm).

The first argument for find is the "location to search", and then you specify the "search query" with the various -<option>s. So, the proper format of the command you want to run is:

find "/home/bkp/dbdump" -name "*.gz" -mtime +5 -exec rm -f {} \;

or

find "/home/bkp/dbdump" -name "*.gz" -mtime +5 delete

If you don't specify the PATH definition like above, use:

/usr/bin/find "/home/bkp/dbdump" -name "*.gz" -mtime +5 -exec /bin/rm -f {} \;

or

/usr/bin/find "/home/bkp/dbdump" -name "*.gz" -mtime +5 delete

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-12-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。