If you want to keep 3 generations, you can use the script one liner below. (The idea is to leave 3 generations → read as deleting all files other than the 3 generations you want to keep)
(When erasing from the oldest one in time) ls -1rt | head -n -3 | xargs rm -rf
(When deleting the oldest date such as testlog20200701) ls -1 | head -n -3 | xargs rm -rf
Description (when erasing the old one judging from the character string in the log)
-rw-r--r--. 1 root root 0 May 17 16:40 testlog20200701 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200702 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200703 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200704 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200705 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200706 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200707 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200708 -rw-r--r--. 1 root root 0 May 17 16:40 testlog20200709
testlog20200701 testlog20200702 testlog20200703 testlog20200704 testlog20200705 testlog20200706
Verification
testlog20200707 testlog20200708 testlog20200709
I was able to leave the desired 3 generations.
*) (When erasing from the oldest one in time) is realized by performing with ls -1rt. Option t Sort by time Option r Sort in reverse
It is assumed that the log rotation itself is performed using the Linux standard logrotate.d, and only the deleted part is performed by the shell script. (Because the deletion script of logrotate.d is processed in the form of x days ago, if the deletion script does not work for some reason, the log may remain)
Recommended Posts