【问题标题】:Cron Job - Delete old files, but keep files from the first of the monthCron Job - 删除旧文件,但保留当月第一天的文件
【发布时间】:2012-08-25 07:31:14
【问题描述】:

我目前正在运行成功的 mysql 备份,并且在某些站点上,我正在使用此命令删除 7 天之前的文件

find  /path/to/file -mtime +7 -exec rm -f {} \;

我想做的,因为我很偏执并且仍然想要一些存档信息,是删除超过 31 天的文件,但至少保留上个月的一个文件,也许保留任何创建的文件每月 1 日。

有什么想法吗?

【问题讨论】:

    标签: unix cron


    【解决方案1】:

    有点难看,但你可以尝试解析ls -l的输出

    rm `find /path/to/file -type f -mtime +7 -exec ls -l {} + | grep -v ' [A-S][a-z][a-z]  1  ' | sed -e 's:.* /path/to/file:/path/to/file:g'`
    

    或者编写一个脚本来获取列表,然后在它们上一次运行rm

    【讨论】:

    • 似乎没有用。它刚刚删除了所有超过 31 天的文件。
    【解决方案2】:

    您还可以使用 xargs 编写一个脚本来包含这样的内容:

    找到 /path/to/files -mtime +7| xargs -i rm {};

    然后将脚本添加到您的 cron 作业中

    【讨论】:

      【解决方案3】:

      grep 几乎是对的,它只有一个空格太多。这有效(至少对我来说,我使用 Debian):

      rm `find /path/to/file -type f -mtime +7 -exec ls -l {} + | grep -v ' [A-S][a-z][a-z]  1 ' | sed -e 's:.* /path/to/file:/path/to/file:g'`
      

      【讨论】:

        【解决方案4】:

        您可以使用以下命令创建文件:

        SRC_DIR=/home/USB-Drive
        DATE=$(/bin/date "+%4Y%2m%2d%2H%2M")
        TIME_STAMP=$(/bin/date --date 'now' +%s)
        TIME_CAL=$[$TIME_STAMP-2592000+25200] #last day, 25200 is my GMT+7hour 
        TIME_LAST=$(/bin/date --date "1970-01-01 $TIME_CAL sec" "+%4Y%2m%2d%2H%2M")
        /bin/touch -t ${TIME_LAST} /tmp/lastmonth
        /usr/bin/find -P -H ${SRC_DIR}  ! -newer /tmp/lastmonth -type d -exec rm -r {} \;
        

        您可以根据要删除的内容修改最后一条命令,在这种情况下,我想删除 SRC_DIR 中的子文件夹。超过 1 个月前的“时间属性”。

        【讨论】:

          猜你喜欢
          • 2010-09-29
          • 1970-01-01
          • 1970-01-01
          • 2021-09-25
          • 2013-11-30
          • 1970-01-01
          • 1970-01-01
          • 2020-01-29
          • 1970-01-01
          相关资源
          最近更新 更多