Shell Script – Delete Files Except N Files with Bigger Name

filesshell-script

I want to create a shell script that deletes old release files except last n files. In other words, only mantain last n releases when I deploy a new release.

File names have this format:

appname_releasenumber_date.tar.gz

Maybe there's an easy soluction to do this, but I cannot figure out how to do this.

I've found this solution Cleaner way to delete files on Linux which include a datestamp as part of file name but I need to generate some files first in order to keep the number of files I want to.

Best Answer

You can search oldest files and then you can check if total number of files are more then N files then delete oldest files first in a script or you can also simply use the following example. Let's say you don't want to delete last 3 latest files:

ls -t1 | tail -n +4 | xargs rm -rf