Skip to content

Instantly share code, notes, and snippets.

@ozydingo
Created December 29, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozydingo/f64f8aea16abac1a8224317848f718b2 to your computer and use it in GitHub Desktop.
Save ozydingo/f64f8aea16abac1a8224317848f718b2 to your computer and use it in GitHub Desktop.
Delete old remote git branches
USAGE="clean_old_remote_branches.sh
Remove branches from remote older than a specified threshold.
Arguments:
-h : print this message
-n, --dry-run : print actions, do not take them.
-d, --days : threshold for \"old\", in days. Default: 200
-l NUM, --limit NUM : do at most NUM branches
-v, --verbose : print out more info
"
DAYS=200
while [ -n "$1" ]; do
case $1 in
-h)
echo $USAGE
exit 0
;;
-n | --dry-run)
DRY_RUN=1
shift
;;
-l | --limit)
LIMIT=$2
shift; shift
;;
-d | --days)
DAYS=$1
shift; shift
;;
-v | --verbose)
VERBOSE=1
shift
;;
*)
echo $USAGE
exit 1
;;
esac
done
count=0
now=$(date +%s)
git branch -r | awk '{print $1}' | while read branch; do
[ -n "$LIMIT" -a $count -ge "${LIMIT-0}" ] && break
read ref author date <<< $(git log $branch -n 1 --date=unix --format="%h %ae %ad")
age=$((now - date))
days=$((age / 60 / 60 / 24))
remote=$(echo $branch | cut -d/ -f1)
branchname=$(echo $branch | cut -d/ -f2-)
remove=0
[ $days -gt $DAYS ] && remove=1
if [ $remove = 1 ]; then
count=$((count + 1))
[ $DRY_RUN = 1 ] && echo "$count: $branch ($ref, $author): age = $days days"
[ $DRY_RUN = 1 ] && echo [DRY RUN] git push "$remote" --delete "$branchname"
[ $DRY_RUN = 0 ] && git push "$remote" --delete "$branchname"
elif [ "$VERBOSE" = 1 ]; then
echo "$count: $branch ($ref, $author): age = $days days"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment