简体   繁体   中英

Removing old folders in bash backup script

I have a bash script that rsyncs files onto my NAS to the directory below:

mkdir /backup/folder_`date +%F`

How would I go about writing a cleanup script that removes directories older than 7 days old based upon the date in directories name?

使用要删除的模式创建文件夹列表,从列表中删除要保留的文件夹,删除所有其他内容。

#!/bin/bash

shopt -s extglob

OLD=$(exec date -d "now - 7 days" '+%s')

cd /backup || exit 1 ## If necessary.

while read DIR; do
    if read DATE < <(exec date -d "${DIR#*folder_}" '+%s') && [[ $DATE == +([[:digit:]]) && DATE -lt OLD ]]; then
        echo "Removing $DIR."  ## Just an example message. Or we could just exclude this and add -v option to rm.
        rm -ir "$DIR"  ## Change to -fr to skip confirmation.
    fi
done < <(exec find -maxdepth 1 -type d -name 'folder_*')

exit 0

We could actually use more careful approaches like -rd $'\\0' , -print0 and IFS= but I don't think they are really necessary this time.

一个简单的发现如何:

find /backup -name 'folder_*' -type d -ctime 7 -exec rm -rf {} \\;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM