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. |
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 |
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. |