remove all but last 5 directories with shell script and find command
-not sure if this belongs here or on serverfault-
What I want to do it list all directories in a directory and delete all of them, exce开发者_开发技巧pt for the last 5. We have a deployment system in place that will incrementally do something link this:
/var/www/html/build1
/var/www/html/build2
/var/www/html/build3
/var/www/html/build4
/var/www/html/build5
/var/www/html/build6
/var/www/html/build7
/var/www/html/build8
/var/www/html/build9
/var/www/html/build10
This is using up way too much disk space so we only want to keep the last 5 builds.
I came up with the following:
(find /var/www/html/ -type d -name "build*" | sort -r) /var/www/html/build1564 /var/www/html/build1563 /var/www/html/build1560 /var/www/html/build1558 /var/www/html/build1557 /var/www/html/build1556 /var/www/html/build1555 /var/www/html/build1554 /var/www/html/build1553 /var/www/html/build1552 /var/www/html/build1551 /var/www/html/build1550
now all I need to do is add an "offset" to that command, so that the first five directories don't show up. After that, the remaining directories should be removed.
If there are no more than 5 directories, nothing should happen.
I guess I'm still missing two steps here, the offset step and the rm -rf step?
To get everything but firt 5 use tail -n +5.(I think you don't need to reverse the sort then) and to rm them you can use xargs. So you can try this
find /var/www/html/ -type d -name "build*" | sort | tail -n +5 | xargs -I % echo -rf %
(replace echo with rm to do it)
You can't use sort
that way because it doesn't recognize that build10 > build9
, for example. You have to cut off the prefix manually:
for dir in build*
do
echo "${dir#build}"
done | sort -n | head -n -5 | xargs -I '%' echo -r 'build%'
Here is an example that shows where your original code fails:
/tmp $ mkdir build8 build9 build10
/tmp $ find . -type d -name "build*" | sort -r
./build9
./build8
./build10
精彩评论