Skip to content

Instantly share code, notes, and snippets.

@TheToddLuci0
Created May 24, 2019 18:35
Show Gist options
  • Save TheToddLuci0/f8224d1e6b9c08c19604d9f4ef8a9648 to your computer and use it in GitHub Desktop.
Save TheToddLuci0/f8224d1e6b9c08c19604d9f4ef8a9648 to your computer and use it in GitHub Desktop.
Automatically remove old branches that haven't been touched in a while
#!/usr/bin/env bash
######################################################################
# This script delets all branches that have not been commited to in #
# the last 100 days. This is non reversable, so make sure you know #
# you are doing. #
# Author: TheToddLuci0 #
######################################################################
echo "" > deleted.txt
echo "" > toBeDeleted.txt
git fetch -a
git for-each-ref --sort=committerdate --format='%(committerdate:raw) %(refname:short)' > git.txt
# To change how long ago to begin purging, change the 100 below to your desired number of days.
hundred_days_ago=$(date -d 'now - 100 days' +%s)
while read p; do
STR=$p
STR2=$p
DATE=$(echo $STR | cut -d' ' -f 1)
BRANCH=$(echo $STR2 | cut -d' ' -f 3)
SUB=${BRANCH:7}
TYPE=${BRANCH:7:8}
REF=${BRANCH:0:7}
# This line prints the difference in time between the last commit and the cut off date (in seconds). Usefull if you are deleting several thousand branches.
echo $(( DATE - hundred_days_ago ))
if [ $DATE -lt $hundred_days_ago ]; then
if [ $REF = "origin/" ]; then
if [ $TYPE != "release/" ]; then
# Uncomment the line below to delete the old branches.
# git push --delete origin $SUB |& tee -a deleted.txt
sleep .5
# Uncomment the line below to list all the branches that would be deleted.
echo "$SUB is older than 100 days" |& tee -a toBeDeleted.txt
else
echo "**********************************************"
echo " Skipping release $SUB"
echo "**********************************************"
fi
if [ -f .git/packed-refs.lock ]; then
echo "Looks like git broke again. I'll fix it."
sleep 15
rm .git/packed-refs.lock
fi
fi
fi
done <git.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment