Scroll Top

Deleting Stale Branches in git

Share this

Too many remote branches in your repo? Tired of scrolling for days to find your branch? Do you like to keep things tidy?

OF COURSE YOU DO! 

Use the following script, based off various scripts found on stackoverflow.com. It takes one param, the number of months old a branch must be before it’s considered a candidate for deletion.

#!/usr/bin/env bash
 
 
echo "Find and delete branches older than $1 months ago"
read -p "If you want delete branches type 'D', otherwise press 'Enter' and branches will be printed out only: " action
[[ $action = "D" ]] && ECHO="" || ECHO="echo"
 
for b in $(git branch -r --merged origin/develop | sed /\*/d | egrep -v "^\*|master|main|develop"); do
  if [ "$(git log $b --since "$1 months ago" | wc -l)" -eq 0 ]; then
    $ECHO git push origin --delete "${b/origin\/}" --no-verify;
  fi
done 

As always, when copying code and scripts from the internet, read through it and verify it won’t do anything harmful on your system. I’ve used this “as is” on our production repositories so I am comfortable with it but YMMV. Use at your own risk.

Share this

Related Posts

Privacy Preferences
When you visit our website, it may store information through your browser from specific services, usually in form of cookies. Here you can change your privacy preferences. Please note that blocking some types of cookies may impact your experience on our website and the services we offer.