Bulk Deleting Folders based on existing git repos

By evan on Feb 08, 2016

I have a system set up where testers can ‘check out’ a feature branch to test. It sets up a full web environment (at var/www/test/branch_name), for an arbitrary feature and customer. It works great, but a problem quickly arose where we had to manually delete stale test environments.

Since repeating something twice means automating it…

There’s a way to delete all folders except a and b.

shopt -s extglob
rm -rf !(folderA|folderB)

shopt lets you use !(a|b) to not rm a or b.

Then we need to get a list of folders to not delete; this command will get every branch, that starts with “test/”, remove the prepended , replace newlines with |, and remove the last |.

git branch | grep 'test/' | sed 's/\ \ //g' | tr '\n' '|' | sed s'/.$//'
test/FEAT-1|test/FEAT-2|test/FEAT-3|test/FEAT-4

to use that in a shell script,

DIR_KEEP=`git branch | grep 'test/' | sed 's/\ \ //g' | tr '\n' '|' | sed s'/.$//'`
shopt -s extglob
rm -rf !($DIR_KEEP)

In this case, it expands to

rm -rf !(test/FEAT-1|test/FEAT-2|test/FEAT-3|test/FEAT-4)

Success! Throw that on an hourly cron job and it will cull the test directories as the feature branches are merged and deleted.

Leave a Reply

Your email address will not be published. Required fields are marked *