Nai*_*ita 7 ksh shell-script file-management
我想在 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
Run Code Online (Sandbox Code Playgroud)
这些都是每天保存并命名的备份文件backup_$date。这个可以吗?
不,一方面它会破坏包含换行符的文件名。它也比必要的更复杂,并且具有解析 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
Run Code Online (Sandbox Code Playgroud)
请注意,这假设所有文件都位于同一文件系统上,如果不是,则可能会产生意外结果(例如删除错误的文件)。如果有多个硬链接指向同一个 inode,它也无法正常工作。