本文介绍了Bash脚本日志文件的旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的bash脚本产生一个日志文件。现在我想实现一些日志文件轮换。假设第一次被称为 somelog.log ,下一次将其重命名为 somelog.log.1 和新日志文件 somelog.log 。第三次,新日志再次是 somelog.log ,但是 somelog.log.1 strong>重命名为 somelog.log.2 和旧的 somelog.log 改为 somelog.log.1 。
我将能够授予最大的例如5.这是否完成之前(示例脚本),任何建议。
解决方案
尝试这个bash函数,它需要两个参数:
- 文件的最大兆字节数超过了要旋转的数目(否则不要触及)
- 文件名的完整路径。
- number of maximum megabyte the file should exceed to be rotated (otherwise is let untouched)
- full path of the filename.
来源:
函数rotate(){
#最小文件大小以MBi为单位旋转:
本地MB =$ 1
#要旋转的文件名(完整路径)
本地F =$ 2
本地msize =$((1024 * 1024 * $ {MB}))
test -e$ F||返回2
local D =$(dirname$ F)
local E = $ {F ## *。}
local B =$(basename$ F。$ E)
local s =
echorotate msize = $ msize file = $ F - > $ D | $ B | $ E
if [$(stat --printf%s$ F)-ge $ msize];那么
for i在8 9 7 6 5 4 3 2 1 0;
s =$ D / $ B- $ i。$ E
test -e$ s&& mv $ s$ D / $ B - $((i + 1))。$ E
#emtpy命令需要避免退出迭代,如果测试失败:
:
完成&&
mv $ F $ D / $ B-0。$ E
else
echorotate skip:$ F <$ msize,skip
fi
return $?
}
My bash script produces a log file. Now i'd like to implement some log file rotation.
Let's say the first time it's called somelog.log, the next time it's renamed to somelog.log.1 and the new log file somelog.log.
The third time the new log is somelog.log again, but somelog.log.1 is renamed to somelog.log.2 and the old somelog.log to somelog.log.1.
I would be able to grant a maximum of eg 5.
Is this done before (sample script), any suggestions. I appreciate any advice.
解决方案
Try this bash function, it takes two parameters:
source:
function rotate () {
# minimum file size to rotate in MBi:
local MB="$1"
# filename to rotate (full path)
local F="$2"
local msize="$((1024*1024*${MB}))"
test -e "$F" || return 2
local D="$(dirname "$F")"
local E=${F##*.}
local B="$(basename "$F" ."$E")"
local s=
echo "rotate msize=$msize file=$F -> $D | $B | $E"
if [ "$(stat --printf %s "$F")" -ge $msize ] ; then
for i in 8 9 7 6 5 4 3 2 1 0; do
s="$D/$B-$i.$E"
test -e "$s" && mv $s "$D/$B-$((i+1)).$E"
# emtpy command is need to avoid exit iteration if test fails:
:;
done &&
mv $F $D/$B-0.$E
else
echo "rotate skip: $F < $msize, skip"
fi
return $?
}
这篇关于Bash脚本日志文件的旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!