After you have done a lot of work with branches on Git, things might become a bit unwieldy and hard to manage. So it is a good housekeeping practice to regularly cleanup your git branches; both local and remote tracking ones.
One way you can remove remote tracking branches that have been deleted in your remote is:
$ git remote prune origin
Or, if you prefer, you can update your remote branches and prune the deleted ones at the same time:
$ git fetch -p origin
The -p flag tells git to prune remote tracking branches that have been deleted.
But this leaves your local branches untouched and you might end up with lots of unwanted branches if you don’t regularly run the command:
$ git branch -d <branch_name>
Running this command regularly is a good way to stay on top of local branches that need to be deleted, but what to do if there are lots of local branches and you don’t want the hassle of issuing this command once for each branch to be deleted?
There is a nice simple one-liner for that:
$ git checkout master && git branch --merged | grep -v master | xargs git branch -d
Let’s break that command down to understand it:
$ git checkout master && git branch --merged
This makes sure that you are on the master branch (otherwise you might end up deleting the master branch itself) and outputs a list of the branches that have already been merged.
$ grep -v master
This filters out the master branch from the output of the previous command.
$ xargs git branch -d
This uses xargs to pass each one of the lines returned from the previous command chain to the command git branch -d, thus deleting all the branches that have already been merged (apart from the master branch).
You can then list all your branches to relish on your nice and tidy repo:
$ git branch -a