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
share|improve this question

10 Answers 10

up vote 72 down vote accepted

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.

share|improve this answer
    
+N is the Nth so it would be tail -n +11. – Dennis Williamson Jun 2 '10 at 21:49
1  
Oh, I can always figure it out eventually, I just find something non-intuitive about it every time. sed -e 1,10d does exactly what it says: delete the first 10 lines. – Dale Hagglund Jun 2 '10 at 22:24
2  
Perfect, straight-forward answer to this problem. Thank you. – Andrew Ensley Aug 10 '11 at 20:13
2  
I get an error: xargs: illegal option -- d – Jake Sellers May 5 '16 at 22:09
2  
@delinquentme The OP asked for the 10 newest files to be left behind, and by deleting them from the output of ls, the following parts of the pipeline remove all older files. – Dale Hagglund Nov 15 '16 at 11:06

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

share|improve this answer
2  
logrotate is a good answer, but it might be a bit heavy-weight: it needs a config file and it's at least somewhat biased toward logfiles semi-official places. Also, doesn't it assume that it should first rotate the logs (ie, rename .N to .N+1) and then delete the oldest? At least as written, the OP's question doesn't imply the rotation of a fixed name. – Dale Hagglund Jun 12 '10 at 10:04

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 !

share|improve this answer
1  
I think this should be checked as the best answer while the chosen is just a waste of commands ! Good Luck – user3677687 Jun 3 '17 at 9:20
2  
A few points about this solution: (1) Using -mtime 10, as you say, selects files older than ten days for deletion. However, the OP's question asks for the ten oldest, not all files older than ten days. (2) find will traverse the entire directory tree, removing files at any level. Here too, the OP doesn't ask for this behaviour. – Dale Hagglund Jun 7 '17 at 7:51
1  
In the previous comment, I incorrectly said that the OP asked for the ten oldest files to be removed. In fact the OP asks for the ten newest files to be kept, and all older files to be removed. Sorry for the confusion, but in either case, -mtime 10 doesn't quite do what's asked for. – Dale Hagglund Jun 7 '17 at 8:06
    
@DaleHagglund Yes, you're right – Mahyar Damavand Jun 7 '17 at 12:39

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.

share|improve this answer

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
share|improve this answer

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
share|improve this answer
stat -c "%Y %n" * | sort -rn | head -n +10 | \
        cut -d ' ' -f 1 --complement | xargs -d '\n' rm

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 of awk since the latter is not always available

Edit 2: Now handles filenames with spaces

share|improve this answer
    
I usually use 'cut' for the last step because awk isn't always installed on all machines. – Jay Jun 2 '10 at 18:02
    
@Jay- A good point, I'll edit my answer accordingly – bta Jun 3 '10 at 16:37

On a very limited chroot environment, we had only a couple of programs available to achieve what was initially asked. We solved it that way:

MIN_FILES=5
FILE_COUNT=$(ls -l | grep -c ^d )


if [ $MIN_FILES -lt $FILE_COUNT  ]; then
  while [ $MIN_FILES -lt $FILE_COUNT ]; do
    FILE_COUNT=$[$FILE_COUNT-1]
    FILE_TO_DEL=$(ls -t | tail -n1)
    # be careful with this one
    rm -rf "$FILE_TO_DEL"
  done
fi

Explanation:

  • FILE_COUNT=$(ls -l | grep -c ^d ) counts all files in the current folder. Instead of grep we could use also wc -l but wc was not installed on that host.
  • FILE_COUNT=$[$FILE_COUNT-1] update the current $FILE_COUNT
  • FILE_TO_DEL=$(ls -t | tail -n1) Save the oldest file name in the $FILE_TO_DEL variable. tail -n1 returns the last element in the list.
share|improve this answer

Using inode numbers via stat & find command (to avoid pesky-chars-in-file-name issues):

stat -f "%m %i" * | sort -rn -k 1,1 | tail -n +11 | cut -d " " -f 2 | \
   xargs -n 1 -I '{}' find "$(pwd)" -type f -inum '{}' -print

#stat -f "%m %i" * | sort -rn -k 1,1 | tail -n +11 | cut -d " " -f 2 | \
#   xargs -n 1 -I '{}' find "$(pwd)" -type f -inum '{}' -delete 
share|improve this answer
    
look at find's -exec + rather than use xargs and certainly not together. – SiegeX Jun 17 '10 at 6:21

Experiment with this, because I'm not 100% sure it'll work:

cd /backups; ls -at | tail -n +10 | xargs -I{} "rm '{}'"
share|improve this answer
    
Seems you need to remove the l from the ls options. – aioobe Jun 2 '10 at 17:46
4  
Yikes! Telling an inexperienced user to 'experiment' with an incorrect xargs rm command? Wearing our BOFH hat today, are we? – Kilian Foth Jun 2 '10 at 17:50
1  
I'm more of an "idea" man ;) – barrycarter Jun 2 '10 at 17:51
    
Ha, I am experimenting with it in a safe location. So, that didn't work, it tells me "No such file or directory" for each file there is... – Nic Hubbard Jun 2 '10 at 17:57
1  
Also, it chokes when the file names have spaces in them... – Nic Hubbard Jun 2 '10 at 17:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.