15일이 지난 파일 삭제(월간 및 연간 버전 제외)

15일이 지난 파일 삭제(월간 및 연간 버전 제외)

간단한 찾기 스크립트를 사용하여 30일이 지난 백업 tar 파일을 삭제하고 있지만 기록을 저장하고 더 자세히 볼 수 있도록 지난 15일과 생성된 모든 백업을 유지하도록 전환하고 싶습니다. 매월 1일(12개월)과 매년 1월 1일(12년을 되돌아보는 날)입니다. 이 작업을 수행하는 가장 우아한 방법은 무엇입니까?

답변1

파일에 올바른 파일 시스템 수준 타임스탬프가 있는 경우그리고날짜는 파일 이름(예: backup-20230713.tar.gz주변)에 포함되며 다음과 같습니다.

# delete files older than 30 days, except ones from the first of each month
find . -name 'backup-*.tar.gz' -mtime +30 ! -name '*-??????01.tar.gz' -delete

# delete files older than a year, except ones from January 1st
find . -name 'backup-*.tar.gz' -mtime +366 ! -name '*-????0101.tar.gz' -delete

# delete everything older than 12 years:
find . -name 'backup-*.tar.gz' -mtime +$(( 12 * 366 )) -delete

또는 파일이 생성될 때 "그룹"을 기준으로 별도의 디렉토리에 파일을 배치하면 됩니다. 예를 들어 매년 첫 번째 날은 yearly/이고 monthly/나머지 도 마찬가지입니다 daily/. 그런 다음 다음을 수행하십시오.

find daily/   -mtime +30 -delete
find monthly/ -mtime +366 -delete
find yearly/  -mtime +$((12 * 366)) -delete

아마도 이와 같은 것을 사용하기 전에 광범위하게 테스트해야 할 것입니다. (etc를 사용하여 테스트 파일을 만들고 etc없이 명령을 touch -d시도하십시오 )find-delete

답변2

면책조항: 저는 이 책의 현재 저자입니다.생가죽(오른쪽 회전) 이 답변에 사용된 프로그램(위치:https://github.com/raforg/rawhide).

오른쪽 회전(그리고찾다)을 사용하면 수정 시간을 정확하게 지정할 수 있는 참조 파일과 수정 시간을 비교할 수 있습니다 touch -t YYYYMMDDhhmm.

다음은 백업 디렉토리에 chdir을 지정하고 지난 12개월 동안 매달 1일과 지난 12년 동안 매년 1월 1일에 대한 타임스탬프가 있는 참조 파일을 생성하는 쉘 스크립트입니다.

그런 다음 호출됩니다.오른쪽 회전파일 목록(사용오른쪽 회전옵션 -l)은 사양에 따라 제거해야 합니다.

-D파일을 삭제하는 옵션이 있습니다 (사용오른쪽 회전옵션 -UUU).

검색 기준은 지정된 날짜(즉, 지정된 시간과 하루 후)에 파일이 마지막으로 수정되었을 때 true를 반환하는 도우미 함수를 정의하는 것으로 시작됩니다.

on(givenday) { mtime >= givenday && mtime < givenday + day }

그런 다음 검색 기준은 ftar 파일( "*.tar*")이고 최소 15일( old(15*days))이 지났으며 마지막 수정 날짜가 지난 12개월 중 어떤 달의 첫 번째 날이 아니거나 첫 번째 날짜가 아닌 일반 파일( )과 일치합니다. 월은 지난 12년 내의 임의 연도의 1월입니다(예: !on("1st00".mtime) && ...).

그런 다음 타임스탬프가 지정된 참조 파일을 삭제합니다.

#!/bin/sh

# Delete backup tarfiles that are older than 15 days except those created
# on the 1st of the month for the past 12 months, and those created on the
# first of January for the past 12 years.

# usage: $0 [-D]
# The -D option deletes files. Without it, they are listed.

# Set this to the path to the backups
path=/path/to/backups

opts=-l
case "$1" in
    -D)
        opts="-UUU"
        ;;
    ?*)
        echo usage: $0 [-D]
        echo "The -D option deletes files (with exceptions)."
        echo "Without it, they will be listed instead."
        echo Files in $path will be listed or deleted.
        exit 1
        ;;
esac

cd "$path" || exit 1

# Create timstamped reference files for the 1st Jan (past 12 years)

year=`date +%Y`
for i in 0 1 2 3 4 5 6 7 8 9 10 11 12
do
    y=`expr $year - $i`
    touch -t ${y}01010000 1stJan`printf %02d $i`
done

# Create timstamped reference files for the 1st of the month (past 12 months)

month=`date +%m`
for i in 0 1 2 3 4 5 6 7 8 9 10 11 12
do
    touch -t $year${month}010000 1st`printf %02d $i`
    if [ $month = 01 ]
    then
        month=12
        year=`expr $year - 1`
    else
        month=`expr $month - 1`
        month=`printf '%02d' $month`
    fi
done

# Delete the backup tarfiles

rh $opts '

    # Define a helper function to make the rest easier to read.
    # True when mtime is on the given day.
    on(givenday) { mtime >= givenday && mtime < givenday + day }

    # Tar files at least 15 days old
    f && "*.tar*" && old(15*days) &&

    # Not last modified on the 1st of the past 12 months
    !on("1st00".mtime) &&
    !on("1st01".mtime) &&
    !on("1st02".mtime) &&
    !on("1st03".mtime) &&
    !on("1st04".mtime) &&
    !on("1st05".mtime) &&
    !on("1st06".mtime) &&
    !on("1st07".mtime) &&
    !on("1st08".mtime) &&
    !on("1st09".mtime) &&
    !on("1st10".mtime) &&
    !on("1st11".mtime) &&
    !on("1st12".mtime) &&

    # Not last modified on the 1st of January for the past 12 years
    !on("1stJan00".mtime) &&
    !on("1stJan01".mtime) &&
    !on("1stJan02".mtime) &&
    !on("1stJan03".mtime) &&
    !on("1stJan04".mtime) &&
    !on("1stJan05".mtime) &&
    !on("1stJan06".mtime) &&
    !on("1stJan07".mtime) &&
    !on("1stJan08".mtime) &&
    !on("1stJan09".mtime) &&
    !on("1stJan10".mtime) &&
    !on("1stJan11".mtime) &&
    !on("1stJan12".mtime)

'

# Clean up the timestamped reference files

rm 1st[01][0-9] 1stJan[01][0-9]

단일 백업 디렉터리에 하드코딩되어 있지만 명령줄에서 사용하기 쉽습니다. 그러나 그렇게 하는 것은 위험할 수 있습니다. 외출할 때는 조심하세요.

같은 일을 할 수 있습니다찾다거의 같은 방식으로 구문이 다르고 구문이 더 많으며 타임스탬프가 있는 참조 파일이 두 배 더 많습니다.

관련 정보