Shell script to count files, then remove oldest files

后端 未结 11 2344
眼角桃花
眼角桃花 2021-01-30 05:29

I am new to shell scripting, so I need some help here. I have a directory that fills up with backups. If I have more than 10 backup files, I would like to remove the oldest fi

11条回答
  •  旧时难觅i
    2021-01-30 05:55

    I just found this topic and the solution from mikecolley helped me in a first step. As I needed a solution for a single line homematic (raspberrymatic) script, I ran into a problem that this command only gave me the fileames and not the whole path which is needed for "rm". My used CUxD Exec command can not start in a selected folder.

    So here is my solution:

    ls -A1t $(find /media/usb0/backup/ -type f -name homematic-raspi*.sbk) | tail -n +11 | xargs rm
    

    Explaining:

    • find /media/usb0/backup/ -type f -name homematic-raspi*.sbk searching only files -type f whiche are named like -name homematic-raspi*.sbk (case sensitive) or use -iname (case insensitive) in folder /media/usb0/backup/
    • ls -A1t $(...) list the files given by find without files starting with "." or ".." -A sorted by mtime -t and with a return of only one column -1
    • tail -n +11 return of only the last 10 -n +11 lines for following rm
    • xargs rm and finally remove the raiming files in the list

    Maybe this helps others from longer searching and makes the solution more flexible.

提交回复
热议问题