Hey guys.

In my workflow at work, we often create merge requests, linked to issues, for tasks or actual issues we come across in our projects.

As I use the terminal in the majority of my work, this can lead to a lot of branches left over on my machine which have already been merged into a staging/development branch.

Typing git branch would often print out whole list of branches which have been dealt with already (which tends not to be easy on the eye).

After a quick search on stack overflow, I found a quick command which will find out which branches have been merged and deleted on the remote repository, and then go on to delete these branches for the local version:

git fetch -p && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -d

This command does the following:

  1. Performs a get to update the local repo with the remote repo
  2. Runs git branch --vv which will echo out a detail list of what branches have been deleted from the remote repo
  3. Perform a awk search to find out which branches have been delete
  4. Using the result of this search, will loop though and delete each branch

For those using bash/zsh, I created an alias for this command so I don't have to remember the whole thing:

alias gclean ="git fetch -p && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -d"

(I use the prefix g as most of my git commands follow the same convention).

Hopes this helps out with someones workflow too!