I often delete the log file 7 days ago and use the date as a condition like rotation, This time I made a bash sample when rotating by specifying the number.
The file to rotate this time is It will be rotated in the format of server.log.YYYY-MM-DD.
/var/log/server.log #Latest file /var/log/server.log.2020-03-25 /var/log/server.log.2020-03-24 /var/log/server.log.2020-03-23 /var/log/server.log.2020-03-22
#!/bin/bash
ROTATE_GEN=7 #Rotation generation (7 left this time)
LOG=/var/log/server.log #Target file
#Save files with date
mv ${LOG} ${LOG}.`date +"%Y-%m-%d"`
#Current number of files(FILE_CNT) -Number of generations(ROTATE_GEN)
# =Number of files to delete(RM_CNT)
FILE_CNT=`ls -1t ${LOG}.* | wc -l`
RM_CNT=`expr ${FILE_CNT} - ${ROTATE_GEN}`
# RM_Delete as many files as there are CNTs
if [[ $RM_CNT -gt 0 ]] ; then
ls -1t ${LOG}.* | tail -n ${RM_CNT} | xargs rm -f
fi