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.
A number of log files are set up for rotation as soon as a Linux system is installed. In addition, certain applications add their own log files and rotation specs when they are installed on the system. The configuration files for log-file rotations can be found in the /etc/logrotate.
If you want to force Logrotate to rotate the log file when it otherwise would not have, use the --force flag: logrotate /home/sammy/logrotate. conf --state /home/sammy/logrotate-state --verbose --force.
In information technology, log rotation is an automated process used in system administration in which log files are compressed, moved (archived), renamed or deleted once they are too old or too big (there can be other metrics that can apply here).
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 $?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With