Quantcast
Channel: CodeSection,代码区,Linux操作系统:Ubuntu_Centos_Debian - CodeSec
Viewing all articles
Browse latest Browse all 11063

关于保留最新文件或清除过期文件的简单总结

$
0
0

在运维工作中经常遇到要管理备份、日志等与时间戳有关的文件,例如删除超过10天的备份/日志文件,保存最新的10个的备份/日志文件等。

“删除超过10天的备份/日志文件”是用的比较多的一种,通常用于定时计划任务,每次产生这些文件都是规律的时间点。

“保存最新的10个备份/日志文件”这种需求通常用在不定时的产生备份(例如每次手动执行一次产生)和日志文件(超过一定的大小则切割)。

两种不同的需求对应不同的方法去实现,无论使用什么样的方法都要找出所需要操作的文件或者去除不需要的文件。

linux Bash Shell代码 “删除超过10天的备份/日志文件” 找出这些超过10天的文件,然后执行删除:

function clean_old_files_older_than_day(){ save_days=10 files_ops="/data/docker/logs/myApp/" need_clean=$(find ${files_ops} -name "*.log" -mtime +${save_days} -exec ls '{}' \;) if [ ! -z ${need_clean} ]; then echo "Old logs have been found, clean old logs now. " find -L ${files_ops} -maxdepth 1 -name "*.log" -a ! -name "^." -mtime +${save_days} -exec rm -rf '{}' \; else echo "All logs are not expired, skipping. " fi }

Linux Bash Shell代码“保存最新的10个备份/日志文件” 找出这些除了最新的10个文件之外的文件,然后执行删除:

function keep_some_newest_files(){ num_save=10 files_ops="/data/backup/db/mysql/" num_files=$(find ${files_ops} -type d -printf "%C@ %p\n" | sort -n | wc -l) if test ${num_files} -gt ${num_save};then echo "total number of files is $num_files." num_ops=$(expr ${num_files} - ${num_save}) echo "$num_ops files are going to be handled." list_ops=$(find ${files_ops} -type d -printf "%C@ %p\n" | sort -n | head -n${num_ops} | awk -F '[ ]+' '{print $2}') # IFS=' '$'\t'$'\n', If IFS is unset, or its value is exactly <space><tab><newline> old_IFS=$IFS IFS=" " for file_ops in ${list_ops};do echo "$file_ops" test -d ${file_ops} && rm -rf ${file_ops} done IFS="$old_IFS" else echo "total number of files is $num_files." echo "0 files are going to be handled, skipping." fi }

tag:日志文件管理,备份文件管理,find删除文件

--end--


Viewing all articles
Browse latest Browse all 11063

Trending Articles