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 files, so that the 10 newest backup files are the only ones that are left.
So far, I know how to count the files, which seems easy enough, but how do I then remove the oldest files, if the count is over 10?
if [ls /backups | wc -l > 10]
then
echo "More than 10"
fi
Straightforward file counter:
Breakdown: Get last-modified times for each file (in the format "
time
filename
"), sort them from oldest to newest, keep all but the last ten entries, and then keep all but the first field (keep only the filename portion).Edit: Using
cut
instead ofawk
since the latter is not always availableEdit 2: Now handles filenames with spaces
Experiment with this, because I'm not 100% sure it'll work:
Make sure your pwd is the correct directory to delete the files then(assuming only regular characters in the filename):
keeps the newest 10 files. I use this with camera program 'motion' to keep the most recent frame grab files. Thanks to all proceeding answers because you showed me how to do it.