LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   BASH script that removes sub-directories (not just files) but keeps the two newest. (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-that-removes-sub-directories-not-just-files-but-keeps-the-two-newest-721003/)

kennc 04-22-2009 04:57 PM

BASH script that removes sub-directories (not just files) but keeps the two newest.
 
Hello. This is my first posting and I'm stuck trying to script this logic together.

The task is to write a script that can be run from cron (preferably bash) that will recursively delete directories as a cleanup task. That part I can do without too much difficulty thanks to the many examples on this forum. However, an added piece is that I need the script to leave the two *newest* created directories intact. The objective is to always have the two newest directories available, but prune older ones as time goes on.

If the script is run against a directory that only has two sub-directories, it should exit and do nothing.

Any help would be appreciated. I'm working on FC8.

Tinkster 04-22-2009 07:01 PM

Hi, welcome to LQ!

To be able to assist you with this will depend on whether or not all
directories will be written in an ongoing manner; since Linux doesn't have
a "creation time stamp" it's quite important to know the above. If
they are you probably want to integrate the creation time/date into
the directories names - in which case all you need to do to keep
the last two is to "ls | head -n -2" which will give you all but the
last two entries (if the names of your directories sort ASCII, that
is, in other words if you name them YYYYMMDDHHMM).


Cheers,
Tink

kennc 04-23-2009 01:09 PM

Thanks for the help
 
That's exactly what I needed. When I get this written up today I'll add it to this post, might actually help someone else too!


All times are GMT -5. The time now is 04:35 PM.