[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 390
  • Last Modified:

Delete oldest files/directories - but not all!

I have an automated process that deposits generated files in subdirs (that it creates) of a fixed directory.  So it looks like

/mydir/20031201/file
/mydir/20031203/file
etc.

What I want to do is setup a cron job that will clean up the mydir directory.  Here's how I want it to work:

I want to delete all the directories (the 20031203-type, not mydir), and their files, EXCEPT for the newest 10.  So if there's only 10 dirs or less when the cleanup script runs, it does nothing.  If there are 33 dirs, it deletes the 23 oldest.

I'm trying to do this with ls -c, and then pipe through head and/or tail, but I just can't see a way to do it that way.

How can I write a script that will do this?
0
kwd
Asked:
kwd
  • 2
1 Solution
 
Karl Heinz KremerCommented:
The command "ls -t /mydir/*" lists all directories ordered by their creation time. The newest is first, and the oldest last. All you now have to do is strip off the first 10 names: The command "tail +11" does exactly this: It lists all lines starting with the 11th. If you now combine these commands, and call rm -rf on all lines, you are done:

ls -t /mydir/* | tail +11 | xargs /bin/rm -rf
You should however test this first with the echo command instead of /bin/rm:
ls -t /mydir/* | tail +11 | xargs echo


0
 
Karl Heinz KremerCommented:
BTW: I used -t (modification time) instead of -c (creation time) because I would want to keep a directory that was recently modified around for a little while
0
 
kwdAuthor Commented:
Brilliant, thanks.  I missed the "+" option in man tail, and I didn't know about xargs.  Your script works perfectly!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now