this post was submitted on 15 Apr 2025
5 points (100.0% liked)

Linux

1996 readers
1 users here now

Everything about Linux

RULES

founded 2 years ago
MODERATORS
 

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...

top 2 comments
sorted by: hot top controversial new old
[โ€“] [email protected] 1 points 2 months ago

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

[โ€“] [email protected] 1 points 2 months ago

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.