删除所有早于X天的文件,但至少保留Y天最年轻 [英] Remove all files older than X days, but keep at least the Y youngest

查看:174
本文介绍了删除所有早于X天的文件,但至少保留Y天最年轻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本可以从备份目录中删除比X = 21天还早的数据库转储:

I have a script that removes DB dumps that are older than say X=21 days from a backup dir:

DB_DUMP_DIR=/var/backups/dbs
RETENTION=$((21*24*60))  # 3 weeks

find ${DB_DUMP_DIR} -type f -mmin +${RETENTION} -delete

但是,如果由于某种原因数据库转储作业在一段时间内无法完成,则所有转储最终都将被丢弃.因此,作为一种保障措施,我希望至少保留最年轻的Y = 7转储,即使其中的全部或部分转储都已超过21天.

But if for whatever reason the DB dump jobs fails to complete for a while, all dumps will eventually be thrown away. So as a safeguard i want to keep at least the youngest Y=7 dumps, even it all or some of them are older than 21 days.

我正在寻找比意大利面更优雅的东西:

I look for something that is more elegant than this spaghetti:

DB_DUMP_DIR=/var/backups/dbs
RETENTION=$((21*24*60))  # 3 weeks
KEEP=7

find ${DB_DUMP_DIR} -type f -printf '%T@ %p\n' | \  # list all dumps with epoch
sort -n | \                                         # sort by epoch, oldest 1st
head --lines=-${KEEP} |\                            # Remove youngest/bottom 7 dumps
while read date filename ; do                       # loop through the rest
    find $filename -mmin +${RETENTION} -delete      # delete if older than 21 days
done

(此代码段可能有一些小错误-忽略它们.这是为了说明我可以提出的建议以及为什么我不喜欢它)

(This snippet might have minor bugs - Ignore them. It's to illustrate what i can come up with myself, and why i don't like it)

查找选项"-mtime"是一次性的:-mtime +21"实际上表示至少22天".这总是让我感到困惑,所以我改用-mmin.仍然是一次性的,但只有一分钟.

The find option "-mtime" is one-off: "-mtime +21" means actually "at least 22 days old". That always confused me, so i use -mmin instead. Still one-off, but only a minute.

推荐答案

使用find获取足以删除的所有旧文件,用tail过滤掉最小的$KEEP,然后将其余文件传递给xargs.

Use find to get all files that are old enough to delete, filter out the $KEEP youngest with tail, then pass the rest to xargs.

find ${DB_DUMP_DIR} -type f -printf '%T@ %p\n' -mmin +$RETENTION |
  sort -nr | tail -n +$KEEP |
  xargs -r echo

如果报告的文件列表是要删除的列表,请用rm替换echo.

Replace echo with rm if the reported list of files is the list you want to remove.

(我假设所有转储文件的名称中都没有换行符.)

(I assume none of the dump files have newlines in their names.)

这篇关于删除所有早于X天的文件,但至少保留Y天最年轻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆