7개가 넘는 경우 디렉터리에서 가장 오래된 파일을 삭제합니다.

7개가 넘는 경우 디렉터리에서 가장 오래된 파일을 삭제합니다.

일일 다운로드는 디렉토리에 저장됩니다.

이 폴더에 있는 파일 수를 계산하는 스크립트가 생성되었습니다.

제가 고민하고 있는 부분은 파일이 7개 이상인 경우 디렉터리에서 가장 오래된 파일을 삭제하는 것입니다.

어떻게 진행해야 하나요?

# If I tared it up would the target exist
tar_file=$FTP_DIR/`basename $newest`.tar
if [-s "$tar_file" ]
then
    echo Files Found
else
    echo No files
fi

# tar it up
tar -cf tar_file.tar $newest

# how many tar files do I now have
fc=$(ls | wc -l)
echo $fc

# If more than 7 delete the oldest ones

답변1

나는 이것이 오래된 질문이라는 것을 알고 있습니다. 하지만 다른 사람이 필요할 경우를 대비해 여기에 도착하여 공유했습니다.

#!/bin/bash
FTP_DIR=/var/lib/ftp # change to location of dir
FILESTOKEEP=7

ls -1t $FTP_DIR/*.tar | awk -v FILESTOKEEP=$FILESTOKEEP '{if (NR>FILESTOKEEP) print $0}' | xargs rm

기본적으로 모든 파일을 하나의 열에 나열하고 -1수정 시간을 기준으로 최신 파일부터 정렬합니다.-t

그런 다음 I를 사용하여 awk지정된 파일 수로 var를 설정 $FILESTOKEEP 하고 해당 수보다 큰 레코드를 인쇄합니다.

각 출력 라인에서 실행될 xargs결과 를 전달합니다.rmawk

ls와일드카드를 사용하면 확장 경로가 강제로 인쇄되므로 파일이 저장된 폴더 내에서 스크립트가 호출되지 않으면 이 방법이 작동합니다 .

답변2

tar 파일을 삭제하려고 하는지 $newest 파일을 삭제하려고 하는지 확실하지 않습니다. 그러나 단일 디렉토리에 있는 일반 파일의 경우:

ls -t1 $dir | tail -n +8 | while read filename; do rm "$filename"; done

a) 파일이 7개 미만이고 b) 파일 이름에 공백(줄 바꿈 제외)이 있는 경우 주의해야 합니다.

tail명령은 처음부터 마지막 ​​몇 줄을 가져오려면 양수를 사용할 수 있습니다.

답변3

암호

[vagrant@localhost ~]$ cat rm_gt_7_days
d=/tmp/test
fc=$(ls $d| wc -l)

if [ "$fc" -gt "7" ]; then
        find $d/* -mtime +7 -exec rm {} \;
fi

시험

디렉터리 및 파일

mkdir /tmp/test && \
for f in `seq 7`; do touch /tmp/test/test${f}; done && \
touch -t 201203101513 /tmp/test/test8

개요

[vagrant@localhost /]$ ll /tmp/test
total 0
-rw-r--r--. 1 root root 0 Sep 14 12:47 test1
-rw-r--r--. 1 root root 0 Sep 14 12:47 test2
-rw-r--r--. 1 root root 0 Sep 14 12:47 test3
-rw-r--r--. 1 root root 0 Sep 14 12:47 test4
-rw-r--r--. 1 root root 0 Sep 14 12:47 test5
-rw-r--r--. 1 root root 0 Sep 14 12:47 test6
-rw-r--r--. 1 root root 0 Sep 14 12:47 test7
-rw-r--r--. 1 root root 0 Mar 10  2012 test8

스크립트 실행 및 결과

[vagrant@localhost ~]$ sh rm_gt_7_days
[vagrant@localhost ~]$ ll /tmp/test
total 0
-rw-r--r--. 1 root root 0 Sep 14 12:47 test1
-rw-r--r--. 1 root root 0 Sep 14 12:47 test2
-rw-r--r--. 1 root root 0 Sep 14 12:47 test3
-rw-r--r--. 1 root root 0 Sep 14 12:47 test4
-rw-r--r--. 1 root root 0 Sep 14 12:47 test5
-rw-r--r--. 1 root root 0 Sep 14 12:47 test6
-rw-r--r--. 1 root root 0 Sep 14 12:47 test7

원천

  1. https://askubuntu.com/questions/62492/how-can-i-change-the-date-modified-created-of-a-file
  2. http://www.dreamsyssoft.com/unix-shell-scripting/ifelse-tutorial.php
  3. http://www.howtogeek.com/howto/ubuntu/delete-files-older-than-x-days-on-linux/
  4. http://www.cyberciti.biz/tips/how-to-generate-print-range-sequence-of-numbers.html

답변4

if [ $file_count -gt 7 ]
    rm `/bin/ls -rt | head -1`
fi

관련 정보