Shell

用於保留最近 3 天、最近 3 周和最近 3 個月的備份的 Shell 腳本

  • March 25, 2014

由於我缺乏外殼知識,我不完全確定如何做到這一點。

NOW=$(date +"%Y.%m.%d.%T")

tar czf /backups/web_backup_$NOW.tgz /web/

你能幫我刪除舊的備份,以便它只保留:

  1. 過去 3 天
  2. 過去 3 週各備份一份
  3. 過去 3 個月各備份一份

像這樣:(只是一個想法)

mkdir -p monthly
mkdir -p weekly

ln backup_$NOW.tgz weekly/

# find current month
month=$(date +%Y-%m-)
# find the first file of the current month in the weekly folder
first_monthly=$(ls --sort=time -1 weekly/*$month* 2>/dev/null | tail -1)
# and put it in the monthly folder
ln -f $first_monthly monthly/

# we need only 5 weekly backups
ls --sort=time -1 weekly/* 2>/dev/null | tail -n+6 >> /tmp/deletebackups.txt
# we need only 5 monthly backups
ls --sort=time -1 monthly/* 2>/dev/null | tail -n+6 >> /tmp/deletebackups.txt

# delete the extra files
#rm $(cat /tmp/deletebackups.txt) 2>/dev/null
xargs --arg-file /tmp/deletebackups.txt rm

引用自:https://serverfault.com/questions/185431