Removing older version files

Hi,

I have a direcory as mentioned below:
/development/arun/cycdt/
unser the above i have directories
/2013
/2012
/2011
......
.....
/2000
I need to write a script which can delete the nth version of the directories.
as in if n=10 then the script should arrange the directories in descending creation order and delete all the directories apart from the recent 10 directories

Any help appreciated!!!

#! /bin/bash

n=$1
x=`ls -l | wc -l`
for y in $(ls -1t | tail -$(( $x - $n ))); do rm -rf $y; done
1 Like

Since ls is run twice, there's a race condition. If a directory is deleted in the meantime, a directory that should have been kept will be nuked. Similarly, if a directory is added in the meantime, a directory that should have been removed will persist.

There is no need to run ls twice. You can just use tail's ability to index releative to the beginning of the data, tail -n +10 versus tail -n 10 . However, this approach still requires some arithmetic, since skipping the first x lines requires an option argument of x+1.

I wouldn't bother with tail. In my opinion, the simplest solution is to use sed:

ls -t | sed 1,10d | xargs rm -rf

Note that xargs does not play well with filenames containing whitespace or quotes. If such filenames occur, instead of xargs, a less efficient while-read loop would be necessary.

ls -t | sed 1,10d | while IFS= read -r dirname; do rm -fr "$dirname"; done

Regards,
Alister

Or, eve