linux shell脚本清理日志文件
时间:2015-02-07 20:38 来源:linux.it.net.cn 作者:IT
一例shell脚本,用于自动清理日志文件,find -type f -print与xargs参数结合删除linux日志文件的方法。
功能描述:
1、做自动部署系统时精简的一个shell脚本,主要功能是清理所有目录的日志文件。
2、根据给定日志目录,删除时间 结合crontab进行清理日志,清理完成后,后在/var/log/deltelog/ 生成按照月的清理linux日志文件。
3、扩展:shell脚本采用mtime(最后修改时间)进行删除,可以适用于删除过期备份等,不受文件名称的限制。
shell技巧:
find –type f –print 时会根据换行或空格来输出查找的文件,在不同的sh下有不同的反应,如果不做处理结合xargs 进行删除更改操作,会有影响。
需要增加 –print0 用 null来 作为边界符号,才敢结婚 xargs –o 来格式化输入。
使用linux find命令时,要遵循最小结果集原则,find解析式从左到右,所有确保你在最左边的过滤符号能够过滤最大数据。
可以根据需要设置计划任务,将脚本添加到crontab中。
shell脚本:
代码示例:
#!/bin/sh
###########################
#delete log blog.duplicatedcode.com
# in_day_num: like 1 2 is delete 2day ago logs
# in_log_path like tomcat log home
###########################
in_log_path=${1}
in_day_num=${2}
tmp_delete_log=/var/log/deletelog/"`date +%Y%m`.log"
deleteLog()
{
inner_num=${1}
#find log
echo "[`date`] >> start delete logs---" >> $tmp_delete_log
find ${in_log_path} -type f -mtime ${inner_num} -print0 | xargs -0 rm -rf
echo "[`date`] >> end delete logs---" >> $tmp_delete_log
}
init()
{
mkdir -p /var/log/deletelog/
}
main()
{
init
if [ -z ${in_log_path} ];then
echo "[`date`] >> error log_path not init---" >> $tmp_delete_log
return
fi
inner_day_num=+7
if [[ -n ${in_day_num} ]] && [[ ${in_day_num} -ge 1 ]] ; then
${inner_day_num}=${in_day_num}
fi
deleteLog ${inner_day_num}
}
main
(责任编辑:IT)
一例shell脚本,用于自动清理日志文件,find -type f -print与xargs参数结合删除linux日志文件的方法。
功能描述:
shell技巧: 使用linux find命令时,要遵循最小结果集原则,find解析式从左到右,所有确保你在最左边的过滤符号能够过滤最大数据。 可以根据需要设置计划任务,将脚本添加到crontab中。
shell脚本:
#!/bin/sh
########################### #delete log blog.duplicatedcode.com # in_day_num: like 1 2 is delete 2day ago logs # in_log_path like tomcat log home ########################### in_log_path=${1} in_day_num=${2} tmp_delete_log=/var/log/deletelog/"`date +%Y%m`.log" deleteLog() { inner_num=${1} #find log echo "[`date`] >> start delete logs---" >> $tmp_delete_log find ${in_log_path} -type f -mtime ${inner_num} -print0 | xargs -0 rm -rf echo "[`date`] >> end delete logs---" >> $tmp_delete_log } init() { mkdir -p /var/log/deletelog/ } main() { init if [ -z ${in_log_path} ];then echo "[`date`] >> error log_path not init---" >> $tmp_delete_log return fi inner_day_num=+7 if [[ -n ${in_day_num} ]] && [[ ${in_day_num} -ge 1 ]] ; then ${inner_day_num}=${in_day_num} fi deleteLog ${inner_day_num} } main (责任编辑:IT) |