IT/라즈베리파이2

오래된 파일 자동 지우기(crontab)

단디1969 2015. 7. 5. 12:13

* 명령자동실행Crontab(Quick Reference) 활용

 

리눅스 n일 이상 된 폴더 보기, 삭제하기

 

IP Cam에서 보낸 영상을 RPI2에 연결된 외장하드에 저장하고 있는데 용량관리를 위해 설정된 시간이 지난 파일은 자동으로 삭제되도록 할 수 있다. crontab을 활용하여 아래와 같이 해보자.

 

원문 : http://www.linuxbrigade.com/delete-files-x-days-old/

 

Delete files that are x days old

 

Rob —  September 6, 2013 — 5 Comments

Sometimes in Linux, you want to clear out older files in a directory. one instance would be if you have a security system and it continuously writes video files to a directory on your NAS (Network Attached Storage) until it fills it up. You’ve figured out that if you keep a week’s worth of video, it will usually leave plenty of space for other users.

What I would suggest here is creating a cron job that runs every night and runs something like the following command:

 

find /path/to/files/ -type f -mtime +7 -exec rm -rf {} \;


find 
: the command that will search for the files 

/path/to/files/ : the top level directory to start searching

-type f : so we don’t remove directories, only files

-type d : remove directories

-mtime +7 : files older than ‘7’ days. Change to ‘+14′ to delete files older than 2 weeks.

-atime => access time ; 접근했던 시간(실행, reading등), 

 ls -lu 명령으로 확인가능

-ctime => change time ; 화일의 속성에 변화가 있은 시간(퍼미션, owner 등)

 ls -lc 로 확인가능

-mtime => modify time ; 화일의 내용을 수정한 시간.                          

 ls -l로 확인 가능

-7 : 7일 미만, 6일전,5일전 .....1일전, 오늘 수정된 파일이나 폴더

 7 : 딱 7일 전에 수정한 화일만 해당

+7 : 7일 초과된 즉 8일전,9일전 ..... . 여기서 숫자 단위는 하루(24시간)임.

-exec : what to do with the files we find

rm -rf : remove them recursively, force

{} : this represents each file we find

\; : the end of the exec

 

SO – the crontab entry would be this:

 

sudo crontab -e

 

- 하기내용을 추가하고 저장하고 나온다.

 

 

예제)

50 23 15* * find /home/exHDD/cctv1/ -type f -mtime +31 -exec rm -rf {} \;

 

: 매월 15일 밤 11시 50분에 /home/exHDD/cctv1 폴더 밑의 파일 및 폴더를 검색해서 31일을 초과한 것만 삭제 

 

: 50 23 1 * * => minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday)

 

50 23 26 * * find /home/exHDD/cctv1/ -mtime +365 -exec rm -rf {} \;

: 매월 26일 23시 50분에 cctv1폴더 밑의 365일 지난 폴더 및 파일 삭제