I would like to share two useful Scripts that I recently created to address multiple old merged branches, no longer necessary.

How to list merged repositories

git branch -r --merged | grep -v master | 
grep -v Any-Branch-To-Be-Removed |sed 's/origin\///'

Please note we are excluding anything that contains on its name =>
master and Any-Branch-To-Be-Removed, you can repeat this pattern for any sensitive branch you DO NOT want to remove, typically Testing branches.

How to list and delete merged repositories

git branch -r --merged | grep -v master
| grep -v Any-Branch-To-Be-Removed |sed 's/origin\///'
| xargs -n 1 git push --delete origin

Essentially same script, added more commands at the end, deleting branches remotely/origin.

Script Breakdown

  • git branch -r –merged => Shows all branches on remote (-r) that is merged (–merged)
  • grep => Matches each resulting line into a string, then (-v) excludes from the list
  • sed => String Replace, where
    • s means substitute
    • / it is like a separator, breaking down all parameters
    • origin/ string to be replaced please note it is escaped by using origin\/
    • / separator
    • / is a string to replace – in this case empty string
  • xargs => Special Unix command line to execute command per each previous result, either separated by space or line

References: