特定の時間に実行されるcronjobにスクリプトを配置し、ファイル数が60を超える場合は、フォルダから最も古いファイルを削除したいと思います。後入選出法。頑張りましたが、
#!/bin/ksh
for dir in /home/DABA_BACKUP
do
cd $dir
count_files=`ls -lrt | wc -l`
if [ $count_files -gt 60 ];
then
todelete=$(($count_files-60))
for part in `ls -1rt`
do
if [ $todelete -gt 0 ]
then
rm -rf $part
todelete=$(($todelete-1))
fi
done
fi
done
毎日保存され、名前が付けられているバックアップファイルbackup_$date
。これは大丈夫ですか?
ベストアンサー1
いいえ、まず改行を含むファイル名が破損します。また、必要以上に複雑で、次のようなすべてのリスクを抱えています。lsを解析する。
より良いバージョンは次のとおりです(GNUツールを使用)。
#!/bin/ksh
for dir in /home/DABA_BACKUP/*
do
## Get the file names and sort them by their
## modification time
files=( "$dir"/* );
## Are there more than 60?
extras=$(( ${#files[@]} - 60 ))
if [ "$extras" -gt 0 ]
then
## If there are more than 60, remove the first
## files until only 60 are left. We use ls to sort
## by modification date and get the inodes only and
## pass the inodes to GNU find which deletes them
find dir1/ -maxdepth 1 \( -inum 0 $(\ls -1iqtr dir1/ | grep -o '^ *[0-9]*' |
head -n "$extras" | sed 's/^/-o -inum /;' ) \) -delete
fi
done
これは、すべてのファイルが同じファイルシステムにあると仮定します。そうしないと、予期しない結果(誤ったファイルの削除など)が発生する可能性があります。同じ inode を指す複数のハードリンクがある場合でも、正常に動作しません。