오래된 파일을 삭제하되 주/월/년마다 하나씩 보관하세요.

오래된 파일을 삭제하되 주/월/년마다 하나씩 보관하세요.

10분마다 로그 파일이 있는 폴더가 있습니다.

alfred_140810-190001.json
alfred_140810-191001.json
alfred_140810-192002.json
alfred_140810-193001.json
alfred_140810-194001.json
alfred_140810-195001.json
alfred_140810-200002.json
alfred_140810-201119.json
alfred_140810-202002.json
...

어떻게 이를 달성할 수 있나요?

  • 일주일이 지난 모든 파일을 삭제하되 일주일에 하나씩 보관하세요.
  • 한 달이 지난 모든 파일을 삭제하되 한 달에 한 개씩 보관합니다.
  • 1년이 지난 모든 파일을 삭제하되 매년 하나씩 보관하세요.

rsnapshot그래서 지난 4주 동안의 파일 하나(4개), 한 달에 하나의 파일(12개 파일), 연간 하나의 파일( 백업 정렬과 동일한 시스템) 을 원합니다 .

답변1

로그 회전을 원합니다http://linuxcommand.org/man_pages/logrotate8.html.

이미 시스템에 있을 수도 있습니다. 구성하기 만하면됩니다. 그러나 주요 목적은 오래된 로그 파일을 지우는 것입니다. 로그 파일을 유지하도록 구성할 수 있는지는 모르겠습니다.

당신은 무엇을 할 수 있나요

log, log.weekly, log.monthly및 여러 디렉토리를 생성합니다.log.yearly

log모든 로그 파일의 위치입니다. 만들다

  • log에서 으로 최신 로그 파일을 복사하는 주간 크론 작업 log.weekly,
  • 최신 로그 파일을 에서 로 복사하는 월간 크론 log작업log.monthly
  • log에서 으로 최신 로그 파일을 복사하는 연간 크론 작업입니다 log.yearly.

그런 다음 다른 디렉터리에 맞게 logrotate를 구성합니다.

    #!/bin/bash

    NOW=$(date +%


    ls -rt1 ${LOG} | while read FILE
    do
        TVAL=$(stat --printf %W ${LOG}/${FILE})
        if [ $(ls -1 ${LOG.WEEKLY} | wc -l) ] -eq 0 ]
        then
             cp ${LOG}/${FILE} ${LOG.WEEKLY}/${FILE}
        else
             LAST_WEEKLY=$(ls -t1 ${LOG.WEEKLY} | head -n 1 | stat --printf %W)
             if [ $((${TVAL}-${LAST_WEEKLY})) -gt $((60*60*24*7)) ]
             then
                 cp ${LOG}/${FILE} ${LOG.WEEKLY}/${FILE}
             fi
        fi
   # repeat the above logic for month and year
   rm ${LOG}/${FILE} 
   done

답변2

좋아, 로그가 매일 생성된다고 가정하면 다음과 같이 할 것입니다.

#!/bin/sh
day=$(date +%u)#To get a day of the week
day_num=$(date +%d) #To get the current day
month=$(date +%m) #To get the current month
year=$(date +%Y) #Get current year
date=$(date +%Y%m%d) #Get current date

if [ $day -eq 7 ] #Saving only Sunday log
then
    sunday_day=$(date +%Y%m%d) # Saving sunday day
    for (( i = 1; i < 7; i++ )) 
    do
        past_day=$(date -d "-$i day" +%Y%m%d)
        rm "alfred_"$past_date"_*" #Delete six older files so it deletes up to last monday
    done
fi

if [ $day_num -eq 1 ]
then
    for (( h = 2; h <= 31; h ++))
    do
        first_day=$(date +%Y%m%d)
        past_month=$(date -d "-1 month" +%Y%m$h) 
        if [ $past_month -ne $sunday ]
        then
            rm "alfred_"$past_month"_*" #Delete all last month but keep sundays' backup and the first day of that month
        fi
    done
fi

1월의 첫 번째 로그만 일년 내내 유지됩니다.

관련 정보