Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - Clean up of old branches

Tags:

git

branch

github

I have several branches on my current git repo. Most of them have been used to test new features which have been eventually abandoned, a few of them have been implemented and merged to my master. Another one (call it master2) refers to a different concept of the same code I am working on (and probably deserves its own branch, but since it is frozen for now I'd just like to keep it there until I find time to devote to it).

My question is: how do I remove all old and now unused branches, apart from master and master 2 ?

I do not mind keeping all the old history on the remote repository, but neither I mind to much about losing them. My goal is to avoid old stuff to clutter my autocompletion when I work on the repo locally.

Other question I have browsed seem to be looking to much more sofisticated/specialized scenarios where one wants to keep all branches merged to master or similar combinations. I do, instead, want (in a sense) to start afresh with only my master and master2 branches visible locally and up to date. In particular, I have some branches which have not been merged, but I'd still like to keep, unlike what's suggested here.

If it is relevant to understand this is a repo for scientific computing.

like image 761
Three Diag Avatar asked Sep 19 '25 14:09

Three Diag


1 Answers

You can remove a branch with the -D switch:

$ git branch -D branch_to_remove

Git doesn't have a built it way to remove all the branches but those two (at least, not to the best of my knowledge), but you could use a simple shell script to do that:

$ git branch -D `git branch | grep -v master`

The grep -v inverts the grep pattern match. If the branches have different names then you can use

$ git branch -D `git branch | grep -v 'master\|another_branch'`

This will remove all branches but the ones named master and another branch.

like image 166
Mureinik Avatar answered Sep 22 '25 02:09

Mureinik