GIT Simplified removal of 'stale' remote branches and their local branches

As you may noticed in my previous posts I use Git in a lot of projects I am working on.

Previous posts:

Git commands I keep forgetting

Update local develop branch without checkout

Git commands I keep forgetting part 2

In the last one I already talked about "Remove local branches when remote branch is already removed". I used this way of removing a lot the last couple of months. But even with these simple command it is still a lot of work to get your local copy clean.

During some searching on the internet I found another great way to make it even simpeler to cleanup the local repository.

List branches that have no remote branch anymore.

git branch -vv

The above command can be used to list branches in a verbose way. And the output will be something like this:

bugfix/BF_Bug1           6a64538 [origin/bugfix/BF_Bug1: gone] Fixed bug1
bugfix/BF_Bug2           b7cf3ea [origin/bugfix/BF_Bug2] Fixed bug2
* develop                ca60d674 [origin/develop] Merged PR 91: Added Feature
feature/SomeGreatFeature ccb8b3f [origin/feature/SomeGreatFeature: gone] Some great feature added
master                   10ed942 [origin/master] Updated README.md

As you can see 2 branches are 'gone', which means the remote branch does not exist anymore. Now you know which branches you can remove from the local repository with the commands:

git branch -d bugfix/BF_Bug1

git branch -d feature/SomeGreatFeature

The above commands are not so hard to learn, but if you have a lot of branches that you want to remove it can be time consuming to remove every branch manualy. To make your life a little bit easier you have to do the following steps:

  1. Find you .gitconfig file which contains the configuration of GIT.
    On my machine the .gitconfig file could be found at: %USERPROFILE%\.gitconfig
  2. It is possible to add alias command in this configuration file and that's excactly what we are going to do. Add the following lines to the .gitconfig file:
    [alias]
    prune-branches = !git remote prune origin && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -d
  3. You can now remove all local branches from which the remote branch is removed. Open a command prompt in you source directory and type the following command:
    git prune-branches
  4. The output will be something like:
    Deleted branch bugfix/BF_Bug1 (was 6a64538).
    
    Deleted branch feature/SomeGreatFeature (was ccb8b3f).

I really like this command, because now I can execute one command that will clean my local repository. Of course you can name the alias whatever you like. Personally I updated my alias to be ' git pb'  which is faster to type than 'git prune-branches'.

I hope I have made you life a little easier by writing this blog!

Happy Coding!