1

我有一个脚本,可以在当前日期之前在备份文件夹中创建文件夹。该脚本每天通过 cron 运行一次。

有没有办法通过文件夹名称删除超过 3 天的文件夹?就像是

日期-3?

有效的脚本:感谢 Jo So。此脚本按日期创建文件夹。压缩文件以进行备份,将它们粘贴在您的备份目录中并清除超过 3 天的备份 :-)

    #!/bin/bash

    cd /home/backups

    mkdir $(date +%Y-%m-%d)

    cd /opt/

    tar -pczf /home/backups/$(date +%Y-%m-%d)/opt.tar.gz code

    cd /var/

    tar -pczf /home/backups/$(date +%Y-%m-%d)/var.tar.gz work

cd /home/backups/
threedaysago=`date -d "3 days ago" +%Y%m%d`

for backup in [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
do
    backupdate=`echo "$backup" | tr -d -`   # remove dashes

    if test "$backupdate" -lt "$threedaysago"
    then
        rm -rf "$backup"
    fi
done
4

2 回答 2

3
threedaysago=`date -d "3 days ago" +%Y%m%d`

for backup in [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
do
    backupdate=`echo "$backup" | tr -d -`   # remove dashes

    if test "$backupdate" -lt "$threedaysago"
    then
        rm -rf "$backup"
    fi
done

独立于 mtime 工作,我可以告诉你它不会在特别奇怪的极端情况下崩溃;-)

于 2012-07-12T10:33:25.003 回答
0

删除超过 3 天的每日备份(“常规文件”类型):

rm -f `find $YOUR_BACKUP_DIR -maxdepth 1 -type f -mtime +3`

find手册页:

   -mtime n
          File's data was last modified n*24 hours ago.  See the  comments
          for -atime to understand how rounding affects the interpretation
          of file modification times.
于 2012-07-12T09:39:31.710 回答