linuxbashlspurge

Delete all files except the newest 3 in bash script


Question: How do you delete all files in a directory except the newest 3?

Finding the newest 3 files is simple:

ls -t | head -3

But I need to find all files except the newest 3 files. How do I do that, and how do I delete these files in the same line without making an unnecessary for loop for that?

I'm using Debian Wheezy and bash scripts for this.


Solution

  • This will list all files except the newest three:

    ls -t | tail -n +4
    

    This will delete those files:

    ls -t | tail -n +4 | xargs rm --
    

    this does not delete dotfiles. if you also want to delete dotfiles then change ls -t to ls -At.

    the double dash (--) after rm is a safeguard against filenames starting with dash. see here for more info: https://unix.stackexchange.com/questions/1519/how-do-i-delete-a-file-whose-name-begins-with-hyphen-a-k-a-dash-or-minus

    this command can fail horribly if the filenames contain spaces or newlines or other funny characters. if your filenames can contain space, or if you plan to use this in a script then you should read these articles: http://mywiki.wooledge.org/ParsingLs and http://mywiki.wooledge.org/BashFAQ/003