Tuesday, July 22, 2014

Remove obsolete GIT branches

I don't know an option to do this in a single command so I am doing it like below:

git checkout master
comm -23 <( git branch | grep -v "/" | grep -v "*" | sort ) <( git branch -r | awk -F '/' '{print $2}' | sort ) | awk '{print "git branch -D " $1}'
# prints 'git branch -D' commands for every obsolete branch. The next step is to apply them manually.

You could modify command to remove obsolete branches automatically (on your own risk):

comm -23 <( git branch | grep -v "/" | grep -v "*" | sort ) <( git branch -r | awk -F '/' '{print $2}' | sort ) | xargs git branch -D 

Another option to remove obsolete branches is:

git for-each-ref --format='%(refname:short) %(upstream)' refs/heads/ | awk '$2 !~/^refs\/(remotes|heads)/' | xargs git branch -D

1 comment:

  1. git for-each-ref --format='%(refname:short) %(upstream)' refs/heads/ | awk '$2 !~/^refs\/(remotes|heads)/' | xargs git branch -D

    ReplyDelete