My bash script produces a log file. Now i'd l开发者_StackOverflow中文版ike 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:
- 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="$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 $?
}
I've just made a bash script for that: 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.
A typical command looks like that:
> ./logrotator.sh -f private/log -m {fileName}.{datetime}.txt -v
精彩评论