Bash 脚本日志文件轮换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3690015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script log file rotation
提问by John Doe
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.1and the new log file somelog.log.
The third time the new log is somelog.logagain, but somelog.log.1is renamed to somelog.log.2and the old somelog.logto 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.
我的 bash 脚本生成了一个日志文件。现在我想实现一些日志文件轮换。
假设第一次它被称为somelog.log,下次它被重命名为somelog.log.1和新的日志文件somelog.log。
第三次新日志又是somelog.log,但是somelog.log.1重命名为somelog.log.2,旧的somelog.log重命名为somelog.log.1。
我最多可以授予例如 5 个。
这是之前完成的吗(示例脚本),任何建议。我很感激任何建议。
回答by bzimage
Try this bash function, it takes two parameters:
试试这个 bash 函数,它需要两个参数:
- number of maximum megabyte the file should exceed to be rotated (otherwise is let untouched)
- full path of the filename.
- 文件应超过旋转的最大兆字节数(否则保持不变)
- 文件名的完整路径。
source:
来源:
function rotate () {
# minimum file size to rotate in MBi:
local MB=""
# filename to rotate (full path)
local F=""
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 $?
}
回答by ling
I've just made a bash script for that: https://github.com/lingtalfi/logrotator
我刚刚为此制作了一个 bash 脚本:https: //github.com/lingtalfi/logrotator
It basically checks your log file's size, and if it exceeds an arbitrary threshold, it copies the log file into a log directory.
它基本上检查您的日志文件的大小,如果超过任意阈值,它会将日志文件复制到日志目录中。
It's cron friendly, or you can use it manually too.
它对 cron 友好,或者您也可以手动使用它。
A typical command looks like that:
一个典型的命令如下所示:
> ./logrotator.sh -f private/log -m {fileName}.{datetime}.txt -v

