Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?
To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.
And just to be clear, there's only one file present, it should never be deleted.
found interesting cmd in Sed-Onliners - Delete last 3 lines - fnd it perfect for another way to skin the cat (okay not) but idea:
With zsh
Assuming you don't care about present directories and you will not have more than 999 files (choose a bigger number if you want, or create a while loop).
In
*(.om[6,999])
, the.
means files, theo
means sort order up, them
means by date of modification (puta
for access time orc
for inode change), the[6,999]
chooses a range of file, so doesn't rm the 5 first.Removes all but the 10 latest (most recents) files
If less than 10 files no file is removed and you will have : error head: illegal line count -- 0
To count files with bash
This version supports names with spaces:
All these answers fail when there are directories in the current directory. Here's something that works:
This:
works when there are directories in the current directory
tries to remove each file even if the previous one couldn't be removed (due to permissions, etc.)
fails safe when the number of files in the current directory is excessive and
xargs
would normally screw you over (the-x
)doesn't cater for spaces in filenames (perhaps you're using the wrong OS?)