cp with backup, limit count

a year ago by MoLoPoLY to c/linux

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

INeedMana 1 point a year ago

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

path: 0 16467559, hotness: undefined, score: 1, children: 0
MoLoPoLY 1 point a year 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.

path: 0 16481490, hotness: undefined, score: 1, children: 0
linux
linux

@discuss.tchncs.de

login for more options
2270
233
1

Everything about Linux

RULES

  • Be nice to each other.

  • No memes or pictures of Linux in the wild.

go to feed...