I have a bunch of log files and I would like to keep only the last 3 (N) files, the most recent ones. How do you do this in bash elegantly?
I have this script but it's kind of long.
The files could be something like:
my-file-pattern.log.2019-10-01
my-file-pattern.log.2019-10-02
my-file-pattern.log.2019-10-03
and so on
My script:
#!/bin/bash
function keepLastNOnly(){
local WORKDIR="$1"
local PATTERN="$2"
local MAX=$3
cd $WORKDIR
COUNT=$(ls -t $WORKDIR | grep $PATTERN|wc -l|grep -o -E '[0-9]+')
while [ $COUNT -gt $MAX ]; do
local TODEL=$(ls -t $WORKDIR | grep $PATTERN |tail -n 1)
rm -rf "$TODEL"
COUNT=$(ls -t $WORKDIR | grep $PATTERN|wc -l|grep -o -E '[0-9]+')
done
}
keepLastNOnly "/MyDirectory/" "my-file-pattern.log" 3
Any shorter way?