且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

bash脚本按文件夹名称删除日期文件夹

更新时间:2022-10-20 19:00:07

  threedaysago =`日期-D4天前+%Y%M%D`对于在备份[0-9] [0-9] [0-9] [0-9]  -  [0-9] [0-9]  -  [0-9] [0-9]

    backupdate =`回声$备份| TR -d -`#删除破折号    如果测试$ backupdate-lt$ threedaysago
    然后
        室射频$备份
    科幻
DONE

独立的mtime的工作,我可以告诉你,它不会在特别奇怪的角落情况下打破; - )

I have a script which creates folders in a backup folder by the current date. This script is run once a day, every day via cron.

Is there a way to remove the folders older than 3 days via folder name? something like

date -3 ?

Script that works: Thank you to Jo So. This script creates a folder by date. Compresses the files for backup, sticks them in your backup directory and clears out backups older than 3 days :-)

    #!/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

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

Work independently of mtime, and I can tell you that it will not break under particularly strange corner cases ;-)