Skip to content

Instantly share code, notes, and snippets.

@thomashartm
Last active April 5, 2018 08:42
Show Gist options
  • Save thomashartm/9ed73c1a1566930d0a6d12b4e272ccb6 to your computer and use it in GitHub Desktop.
Save thomashartm/9ed73c1a1566930d0a6d12b4e272ccb6 to your computer and use it in GitHub Desktop.
Cleans up stale unmerged branches older then 4 months
#!/bin/bash
# vim: set ts=4 sw=4 expandtab tw=79 :
#title :cleanup-stale-unmerged-branches.sh
#description :This script cleans up all unmerged branches older then 4 months, except develop and master
#author :[email protected]
#date :2018-04-04
#version :0.1
#notes :initially based on https://gist.github.com/dominics/1762685
#usage :clean-stale-unmerged-branches.sh unmerged.txt
set -e
c_red=`tput setaf 1 || tput setf 4`
c_yellow=`tput setaf 3 || tput setf 6`
c_reset=`tput sgr0`
oldest_branch_limit=$(date -v-4m +%s)
echo "Retrieving obsolete branches older then timestamp $oldest_branch_limit into $1"
for b in $(git branch --remote --no-merged); do
echo -e $b `git show $b --date=format:'%Y-%m-%d %H:%M:%S' --pretty="format: Last commit: %cd %ae" | head -n 1`;
done > "$1"
echo "Parsing now $1"
while IFS='' read -r line || [[ -n "$line" ]]; do
cols=( $line )
branchname=${cols[0]}
if [ $branchname != "origin/develop" -a $branchname != "origin/master" ]; then
lastdate=${cols[3]}
lasttime=${cols[4]}
last_timestamp=$(date -jf "%Y-%m-%d" $lastdate +%s)
if [ "$last_timestamp" -lt "$oldest_branch_limit" ];then
echo "Going to delete branch: $line"
remote=$(cut -d "/" -f1 <<< $branchname)
qualifiedname=$(sed "s/origin\///" <<< $branchname)
git push $remote ":$qualifiedname"
echo "Deleted $qualifiedname"
fi
else
echo "Detected $branchname. Ignoring it"
fi
done < "$1"
echo "Removing $1"
rm "$1"
echo "All done. Remember to git remote prune $remote"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment