Kevin Sedgley
Kevin Sedgley

Reputation: 1069

Removing all directories except the 10 newest

How in bash would I remove all directories except the newest five created directories (by date created time)?

This is being used by a build script, and we want to clear up old builds. Thanks.

Edit: Date modified time is also fine.

Upvotes: 0

Views: 1363

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

It could be done with ls but parsing ls output is not safe.

As there is no shell builtin to retrieve file time a solution using perl.

perl -e '
    @A = sort {(stat($a))[9]<=>(stat($b))[9]} <*/>;
    rmdir for splice (@A,0,-10)
'

Test

mkdir tmp && cd tmp
for d in {A..Z}; do mkdir "$d"; done
ls

perl -e '
    @A = sort {(stat($a))[9]<=>(stat($b))[9]} <*/>;
    rmdir for splice (@A,0,-10)
'

ls

EDIT: splice(@A,0,-10) could be changed to @A[0..$#A-10], maybe easier to read. To get all elements except the last 10.

Upvotes: 0

Alexander Morley
Alexander Morley

Reputation: 4181

It's not trivial to get a files creation time. See here for reference: https://unix.stackexchange.com/questions/20460/how-do-i-do-a-ls-and-then-sort-the-results-by-date-created

But if your happy to the last modification time instead (which should be fine here?) then something like this one-liner should do.

ls -dt */ | tail -n +6 | xargs rmdir

  • ls -d */ list directories -t lists them in order
  • tail -n +6 prints all but the last five lines
  • xargs rmdir calls rm -r on each of those dirs (or you can use rm -r if they're non-empty)

Upvotes: 6

Related Questions