Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to count files, then remove oldest files

Tags:

linux

bash

shell

People also ask

How do I delete files older than a certain date in Linux?

For just files find /path ! -type f -newermt "YYYY-MM-DD HH:MM:SS" -delete . It saves you from having to pipe everything through xargs, and having to handle filesnames with spaces or other disruptive characters.

How do I remove 7 days old files in Linux?

Your command will look at the top level directory /var/log/mbackups and also descend into any subdirectories, deleting files that match the seven day criterion. It will not delete the directories themselves. For files older than 7 days, you need -mtime +6 (or '(' -mtime 7 -o -mtime +7 ')' ), not -mtime +7 .


Try this:

ls -t | sed -e '1,10d' | xargs -d '\n' rm

This should handle all characters (except newlines) in a file name.

What's going on here?

  • ls -t lists all files in the current directory in decreasing order of modification time. Ie, the most recently modified files are first, one file name per line.
  • sed -e '1,10d' deletes the first 10 lines, ie, the 10 newest files. I use this instead of tail because I can never remember whether I need tail -n +10 or tail -n +11.
  • xargs -d '\n' rm collects each input line (without the terminating newline) and passes each line as an argument to rm.

As with anything of this sort, please experiment in a safe place.


find is the common tool for this kind of task :

find ./my_dir -mtime +10 -type f -delete

EXPLANATIONS

  • ./my_dir your directory (replace with your own)
  • -mtime +10 older than 10 days
  • -type f only files
  • -delete no surprise. Remove it to test your find filter before executing the whole command

And take care that ./my_dir exists to avoid bad surprises !


Make sure your pwd is the correct directory to delete the files then(assuming only regular characters in the filename):

ls -A1t | tail -n +11 | xargs rm

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.


The proper way to do this type of thing is with logrotate.


I like the answers from @Dennis Williamson and @Dale Hagglund. (+1 to each)

Here's another way to do it using find (with the -newer test) that is similar to what you started with.

This was done in bash on cygwin...

if [[ $(ls /backups | wc -l) > 10 ]]
then
  find /backups ! -newer $(ls -t | sed '11!d') -exec rm {} \;
fi

Straightforward file counter:

max=12
n=0
ls -1t *.dat |
while read file; do
    n=$((n+1))
    if [[ $n -gt $max ]]; then
        rm -f "$file"
    fi
done