5
2

cp with backup, limit count

1y 2mon ago by discuss.tchncs.de/u/MoLoPoLY in linux@discuss.tchncs.de

If I copy files with backup (cp --backup=numbered), the old file is renamed to something like oldfile.ext.1. I get my old files. Can this be limited to a certain number of old files, for example 30? I don't want to have keep more than that...

With cp, I don't think so. But I guess you could try using logrotate for that

Unfortunately, logrotate does not work the way I would like it to. I have now created a bash script, which hopefully does what it is supposed to do:

#!/bin/bash
keepCount=30

files=($(ls *.db))
fileCount=${#files[@]}

for (( i=0; i<$fileCount; i++ )); do
	database="${files[$i]}"
	dbarr=($(ls -t $database.*))

	for index in "${!dbarr[@]}"; do
		p=$((index+1))
		if [ $p -gt $keepCount ]; then
			rm ${dbarr[$index]}
		fi
	done
done

Invoked in the respective directory, all *.db files are read into an array, as there can be different DBs per user. The array is then processed in a loop. First, the backup files for the respective DB are read into the array again, sorted by age. This array is then processed and all files whose index +1 is greater than keepCount are removed. This means that the oldest files are always removed and only those that are defined in the keepCount are kept.

Its a little bit more complicated, but it seems to do the job.