【发布时间】:2012-08-21 20:06:21
【问题描述】:
我需要为 Web 服务器编写一个脚本,该脚本将清除超过 14 天的文件/文件夹,但保留最后 7 个文件/目录。到目前为止,我一直在做我的研究,这就是我想出的(我知道语法和命令是不正确的,但只是为了让你明白):
ls -ldt /data/deployments/product/website.com/*/ | tail -n +8 | xargs find /data/deployments/product/website.com/ -type f -type d -mtime +14 -exec rm -R {} \;
这是我对脚本应该如何表现的思考过程(我更喜欢 Windows 批处理):
列出目录内容
If contents is less than or equal to 7, goto END
If contents is > 7 goto CLEAN
:CLEAN
ls -ldt /data/deployments/product/website.com/*/
keep last 7 entries (tail -n +8)
output of that "tail" -> find -type f -type d (both files and directories) -mtime +14 (not older than 14 days) -exec rm -R (delete)
我看过一堆例子,使用 xargs 和 sed,但我就是不知道如何将它们组合在一起。
【问题讨论】:
-
什么决定了 7 个保留的文件是什么?
-
你应该看看
logrotate。 -
“清除超过 14 天的文件/文件夹,但保留最后 7 个文件/目录”这是否意味着:“如果文件的使用期限小于 14 天,或者如果它是目录中有 7 个最新文件”?
-
这意味着在指定位置必须至少有 7 个目录。如果超过 7 个,清除最旧的,最多 14 天。